问题:
**C# 混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集
解决方法:
这两天在使用System.Data.SQLite(1.0.66.0),报错误,上网查找具体解决方法就是修改bin文件夹下面的exe.config文件,在里增加 useLegacyV2RuntimeActivationPolicy="true"属性。具体如下。exe.config修改前如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku = ".NETFramework,Version=v4.0"/>
</startup>
</configuration>
修改后如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku = ".NETFramework,Version=v4.0"/>
</startup>
</configuration>
以上是手动更改exe.config文件可以使程序正常运行,但是使用VS2022自动的打包程序,打包发布之后,这个exe.config文件会自动改回去。发布之后的文件并不能正常运行。又得手动改一下exe.config文件才能运行,这样给客户带来安装上的不便。
经过验证,可以在加载数据库之前检查exe.config的属性,是否存在“useLegacyV2RuntimeActivationPolicy="true"的内容,如果没有就增加这个属性,然后再加截数据库。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace MAINFRAME
{
class ConfigSettings
{
public static void ReadSetting()
{
XmlDocument doc = loadConfigDocument();
XmlElement node = (XmlElement)doc.SelectSingleNode("//startup");
XmlAttribute xmlAttribute = node.Attributes["useLegacyV2RuntimeActivationPolicy"];
if(xmlAttribute ==null)
{
node.SetAttribute("useLegacyV2RuntimeActivationPolicy", "true");
doc.Save(getConfigFilePath());
}
}
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
}
}
在窗口加载的过程如下:
SQLiteHelper mydata;//数据库连接、操作方法封装类
private void Main_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
ConfigSettings.ReadSetting();//检查并调整exe.config文件,方法见上面代码。
mydata = new SQLiteHelper(@Application.StartupPath + "\\datadb.db");
Data_init();
}
通过以上调整,就可以实现程序自动检查并调整exe.config文件属性,不需要再手动修改了。