我想更改我的应用程序查找 app.config 文件的位置。
我知道我可以使用 ConfigurationManager.OpenExeConfiguration() 访问任意配置文件 - 但是,当 .Net Framework 读取配置文件(例如,对于 ConnectionStrings 或 EventSources)时,它会查看默认位置。我想实际更改整个 .Net Framework 的全局位置(当然是针对我的应用程序)。
我还知道我可以使用 AppDomainSetup 更改新 AppDomain 的 app.config 的位置。但是,这不适用于应用程序的主 AppDomain。
我也知道我可以重写函数 Main() 并创建一个新的 AppDomain,然后在那个新的 AppDomain 中运行我的应用程序。但是,这有其他副作用 - 例如,Assembly.GetEntryAssembly() 将返回空引用。
考虑到 .Net 中的其他一切是如何工作的,我希望有一些方法来配置我的应用程序的启动环境 - 通过应用程序 list ,或类似的 - 但我一直找不到哪怕是一线希望朝那个方向。
任何指针都会有所帮助。
大卫穆林
最佳答案
我使用的方法是从 Main() 启动另一个 AppDomain,指定配置文件的"new"位置。
GetEntryAssembly() 没有问题;当从非托管代码调用时它只返回 null - 或者至少它不适合我,因为我使用 ExecuteAssembly() 创建/运行第二个 AppDomain,就像这样:
int Main(string[] args)
{
string currentExecutable = Assembly.GetExecutingAssembly().Location;
bool inChild = false;
List<string> xargs = new List<string>();
foreach (string arg in xargs)
{
if (arg.Equals("-child"))
{
inChild = true;
}
/* Parse other command line arguments */
else
{
xargs.Add(arg);
}
}
if (!inChild)
{
AppDomainSetup info = new AppDomainSetup();
info.ConfigurationFile = /* Path to desired App.Config File */;
Evidence evidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain(friendlyName, evidence, info);
xargs.Add("-child"); // Prevent recursion
return domain.ExecuteAssembly(currentExecutable, evidence, xargs.ToArray());
}
// Execute actual Main-Code, we are in the child domain with the custom app.config
return 0;
}
请注意,我们正在有效地重新运行 EXE,就像 AppDomain 和不同的配置一样。另请注意,您需要有一些“神奇”选项来防止这种情况无休止地发生。
我从更大的(真实的)代码块中精心设计了这个,因此它可能无法按原样工作,但应该可以说明这个概念。
关于c# - 如何更改 app.config 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3632422/