How do I select a .Net application configuration file from a command line parameter?

Darrel Miller picture Darrel Miller · Oct 2, 2008 · Viewed 11.9k times · Source

I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line?

Edit:

It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g.

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config");
currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);

This partially works. I can see all of the keys in the appSettings section but all the values are null.

Answer

Darrel Miller picture Darrel Miller · Oct 2, 2008

So here is the code that actually allows me to actually access the appSettings section in a config file other than the default one.

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Alternate.config");
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);

AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");
string MySetting = section.Settings["MySetting"].Value;