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

前端 未结 5 1452
失恋的感觉
失恋的感觉 2021-01-01 19:20

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 a

5条回答
  •  無奈伤痛
    2021-01-01 19:40

    This is the relevant part of the source for app that uses default config and accepts override via command line:

    Get current or user config into the Config object

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    string defCfgName = Environment.GetCommandLineArgs()[0] + ".config";
    
    if (arg.Length != 0)
    {
        string ConfigFileName = arg[0];
        if (!File.Exists(ConfigFileName))
            Fatal("File doesn't exist: " + ConfigFileName, -1);                
        config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);
    }
    else if (!File.Exists(defCfgName)) Fatal("Default configuration file doesn't exist and no override is set." , -1);
    

    Use the config object

    AppSettingsSection s = (AppSettingsSection)config.GetSection("appSettings");
    KeyValueConfigurationCollection a = s.Settings;
    ConnectionString = a["ConnectionString"].Value;
    

提交回复
热议问题