Thursday, March 25, 2010

Programmaticly Changing the File Attribute of an App.config File.

The requirement for this assignment was to use a command line argument to change the settings of a C# console application. I didn't want to compile the settings into the app itself, but to use an app.config file instead. Here's how it works:


public static bool SetEnvironment(string env)
{
  string configFilePath = string.Empty;

  env = env.ToLowerInvariant();
  switch (env)
  {
    case "dev":
       configFilePath = @"Config\Dev.config";
       break;
    case "prod":
       configFilePath = @"Config\Prod.config";
       break;
    default:
       return false;
  }

  try
  {
    System.Configuration.Configuration config =
       ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    AppSettingsSection appSetSec = config.AppSettings;
    appSetSec.File = configFilePath;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
  }
  catch (Exception ex)
  {
    OfflineDemoTool.WriteError(ex.Message);
    return false;
  }

  return true;
}



One thing that I forgot to do was to make sure that the Config\Dev.config and Config\Prod.config files were set to "Copy if newer" in their properties list, otherwise they won't be copied to the output directory.

Most of this comes straight from the MSDN article found here: http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection.aspx