c# - 如何更改 app.config 的位置

标签 c# .net path app-config

我想更改我的应用程序查找 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/

相关文章:

c# - ToList() 方法在哪里? (可查询)

javascript - 使用 SVG 从现有代码生成大的向上指向的三 Angular 形

c# - 在 C# 中建立 SSL 连接时如何检查无效凭据

c# - 以编程方式为 WPF 单元测试生成按键

windows - 删除的环境变量仍然有效

java - 将 URL 转换为路径而不抛出异常

c# - 使用 Entity Framework 进行多次插入会导致 => 物理连接不可用

c# - Spintax C# ...我该如何处理?

c# - 使用Soap Headers处理错误

c# - 有关结构实现接口(interface)时发生的情况的详细信息