desperate people take desperate measures.
这个在codeproject上看的的一个解决方案,拿来试试,不知道为什么不成功。
原文:http://www.codeproject.com/KB/dotnet/dllappconfig.aspx?msg=2823743#xx2823743xx
需求是:
给Dll添加一个Config文件是不行的. 是因为.NET一般只允许将Running application和一个Config绑定。
而程序一旦启动,The .NET Framework reads the application configuration file into a static hashtable whenever the application domain is first referenced. Once it is read, it cannot be reread or modified.
作者n10sive研究了System.Dll,发现
1. 修改ConfigurationSettings class 的静态变量"_configurationInitialized
" 为false, 就可以“欺骗”.NET Framework, config file还没有读入。
2. null out the "_configSystem
". 使得.NET Framework将config读入内存。
并且作者给出了包装好config参数的类,
如果你在程序中new这个类出来后,将会修改程序默认引用的myproject.vshost.exe.Config为mydll.dll.config
下面是我的理解,找他的方法做了一下,没有成功。
I have a Dll "MyDll.dll", with a "MyDll.dll.config" file:
And I have an App project,
Using this line to get the file path:
string str = MyDllConfig.ConnectionString();
but, when I debug into
MyDll.dll.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="AlgorithmConfigFile" value="CashAcceptType.xml"/>
</appSettings>
<connectionStrings/>
</configuration>
Code
public static string ConnectionString()
{
string cstr;
using (new MyDllConfig())
{
string str = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
cstr = ConfigurationManager.AppSettings["AlgorithmConfigFile"];
}
return cstr;
}
"str" is MyDll.config which is under my execute app path.
but "cstr" is null!
I don't know why
ConfigurationManager.AppSettings["AlgorithmConfigFile"];
can't get the value "CashAcceptType.xml"
园子里是否有兄弟闲的有空,玩玩这个方法,呵呵。
PS:最后发现作者原来已经是CTO了,1977年就开始玩计算机软硬件了,呵呵。
Code
internal class MyDllConfig : IDisposable
{
private string _oldConfig;
private bool _libCompat;
private const string _newConfig = "mydll.dll.config";
// don't forget to rename this!!
internal MyDllConfig()
{
_libCompat = Assembly.GetAssembly(typeof(
ConfigurationSettings)).GetName().Version.ToString().
CompareTo("2.0.0.0") == 0;
_oldConfig = AppDomain.CurrentDomain.GetData(
"APP_CONFIG_FILE").ToString();
Switch(_newConfig);
}
protected void Switch(string config)
{
if ( _libCompat )
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE",config);
FieldInfo fiInit = typeof(
System.Configuration.ConfigurationSettings).GetField(
"_configurationInitialized",
BindingFlags.NonPublic|BindingFlags.Static);
FieldInfo fiSystem = typeof(
System.Configuration.ConfigurationSettings).GetField(
"_configSystem",BindingFlags.NonPublic|BindingFlags.Static);
if ( fiInit != null && fiSystem != null )
{
fiInit.SetValue(null,false);
fiSystem.SetValue(null,null);
}
}
}
public void Dispose()
{
Switch(_oldConfig);
}
public static string ConnectionString()
{
string cstr;
using ( new MyDllConfig() )
{
cstr = ConfigurationSettings.AppSettings["ConnectionString"];
}
return cstr;
}
}