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

前端 未结 5 1432
失恋的感觉
失恋的感觉 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:26

    This is not exactly what you are wanting... to redirect the actual ConfigurationManager static object to point at a different path. But I think it is the right solution to your problem. Check out the OpenExeConfiguration method on the ConfigurationManager class.

    If the above method is not what you are looking for I think it would also be worth taking a look at using the Configuration capabilities of the Enterprise Library framework (developed and maintained by the Microsoft Patterns & Practices team).

    Specifically take a look at the FileConfigurationSource class.

    Here is some code that highlights the use of the FileConfigurationSource from Enterprise Library, I believe this fully meets your goals. The only assembly you need from Ent Lib for this is Microsoft.Practices.EnterpriseLibrary.Common.dll.

    static void Main(string[] args)
    {
        //read from current app.config as default
        AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;
    
        //if args[0] is a valid file path assume it's a config for this example and attempt to load
        if (args.Length > 0 && File.Exists(args[0]))
        {
            //using FileConfigurationSource from Enterprise Library
            FileConfigurationSource fcs = new FileConfigurationSource(args[0]);
            ass = (AppSettingsSection) fcs.GetSection("appSettings");
        }
    
        //print value from configuration
        Console.WriteLine(ass.Settings["test"].Value);
        Console.ReadLine(); //pause
    }
    

提交回复
热议问题