Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#控制台应用程序中动态加载外部App.Config?_C# - Fatal编程技术网

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

如何在C#控制台应用程序中动态加载外部App.Config?,c#,C#,我有一个控制台应用程序,App.Config在appdomain之外,我希望以编程方式加载它(而不是使用powershell)。我已经将外部App.Config的路径作为命令参数传递,但我不知道在运行应用程序后如何将其加载到appdomain中。对于加载App Config,您可以使用以下代码: var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()

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

对于加载App Config,您可以使用以下代码:

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:\drive中。但是你的App.Config应该是这样的,只有appsetting元素才能添加到你的App.Config中

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


参考资料:

从这个链接试试看,我已经看过这篇文章了。区别在于我的应用程序中没有配置文件,生成“filename.exe.config”的配置文件只有一些关于nugets的元数据,仅此而已。有一个配置文件-是外部的,我需要动态加载它。我说的是.NET4.7中的App.config文件-我不是说.NETCore。如果您有其他答案,请再花些时间回复。