如何更改app.config的位置

Dav*_*lin 8 .net c# app-config path

我想更改应用程序查找app.config文件的位置.

我知道我可以使用ConfigurationManager.OpenExeConfiguration()来访问任意配置文件 - 但是,当.Net Framework读取配置文件(例如,对于ConnectionStrings或EventSources)时,它将查看默认位置.我想实际更改整个.Net Framework的位置(当然,对于我的应用程序).

我也知道我可以使用AppDomainSetup来更改app.config的位置以用于新的AppDomain.但是,这不适用于应用程序的主AppDomain.

我也知道我可以覆盖函数Main()并创建一个新的AppDomain,并在新的AppDomain中运行我的应用程序.但是,这有其他副作用 - 例如,Assembly.GetEntryAssembly()将返回空引用.

鉴于.Net中其他所有工作方式,我希望有一些方法来配置我的应用程序的启动环境 - 通过应用程序清单,或者其他一些 - 但我一直无法在这个方向找到一线希望.

任何指针都会有所帮助.

大卫穆林

Chr*_*n.K 9

我使用该方法从Main()启动另一个AppDomain,指定配置文件的"新"位置.

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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们正在有效地重新运行EXE,就像AppDomain和不同的配置一样.另请注意,您需要有一些"魔法"选项,以防止这种情况无休止地进行.

我从一个更大的(真实的)代码块中精心设计出来,所以它可能无法正常工作,但应该说明这个概念.