繁体   English   中英

如何在 C# 控制台应用程序中动态加载外部 App.Config?

[英]How to load external App.Config dynamically in C# Console application?

我有一个控制台应用程序,App.Config 在 appdomain 之外,我想以编程方式加载它(而不是使用 powershell)。 我已经将外部 App.Config 的路径作为命令参数传递了,但是我不知道如何在运行应用程序后将它加载到 appdomain 中。

对于加载应用程序配置,您可以使用以下代码:

var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

var readerConnectionString = builder.Build().GetSection("Parameter")
                                 .GetSection("DbConnectionRead").Value;

这是一个 JSON 示例:

{
    "Parameter":
 {    
    "DbConnectionRead": ""
  }
}

我不确定您是否可以从外部文件夹编辑您的 App.Config。 这是我发现的关于从项目文件夹外的 App.Config 读取 appsettings 的内容。

static void Main(string[] args)
        {
            IntializeConfigurationFile();

            var check = ConfigurationManager.AppSettings["conn"];
        }

static void IntializeConfigurationFile()
        {
            //ConfigurationManager.RefreshSection("appSettings");

            // Get the current configuration associated
            // with the application.
            System.Configuration.Configuration config =
               ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // Associate the auxiliary with the default
            // configuration file. 
            System.Configuration.AppSettingsSection appSettings = config.AppSettings;
            appSettings.File = "C:\\Personal\\Learning\\Docs\\App.config";

            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);

            // Force a reload in memory of the 
            // changed section.
            ConfigurationManager.RefreshSection("configuration");
        }

我已将我的 App.Config 放在 C:\\ 驱动器中。 但是你的 App.Config 应该是这样的,只需要在你的 App.Config 中添加 appsetting 元素。

<appSettings>
        <add key="conn" value="test" />
    </appSettings>

所以基本上它的作用是当您调用 IntializeConfigurationFile IntializeConfigurationFile()方法时,它会将 appsetting 位置写入您的filename.exe.config本地路径。 在我尝试过的项目中是这样添加的

在此处输入图片说明

参考: AppSettingsSection 类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM