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

Viewed 720

I have a console application and the App.Config is outside the appdomain, I want to load it programmatically(not with powershell). I already pass the path of the external App.Config as a command argument but I don't know how to load it in the appdomain once I run the application.

2 Answers

for load app config you can use below code:

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

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

and this is a JSON sample:

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

I am not sure whether you can edit your App.Config from outside folder. Here is something I found about reading appsettings from App.Config outside of project folder.

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");
        }

I have place my App.Config in C:\ drive. But your App.Config should be like this, only appsetting element to be added in your App.Config.

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

So Basically what it does is when you call the IntializeConfigurationFile() method it writes appsetting location to your local path in your filename.exe.config. In the project I have tried was added like this

enter image description here

Reference: AppSettingsSection Class

Related