.net dynamically refresh app.config

前端 未结 10 808
闹比i
闹比i 2020-12-02 23:28

How do I dynamically reload the app.config in a .net Windows application? I need to turn logging on and off dynamically and not just based upon the value at application sta

10条回答
  •  广开言路
    2020-12-02 23:49

    I have tried using the RefreshSection method and got it to work using the following code sample:

    class Program
        {
            static void Main(string[] args)
            {
                string value = string.Empty, key = "mySetting";
                Program program = new Program();
    
                program.GetValue(program, key);
                Console.WriteLine("--------------------------------------------------------------");
                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
    
            /// 
            /// Gets the value of the specified key from app.config file.
            /// 
            /// The instance of the program.
            /// The key.
            private void GetValue(Program program, string key)
            {
                string value;
                if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
                {
                    Console.WriteLine("--------------------------------------------------------------");
                    Console.WriteLine("Key found, evaluating value...");
                    value = ConfigurationManager.AppSettings[key];
                    Console.WriteLine("Value read from app.confg for Key = {0} is {1}", key, value);
                    Console.WriteLine("--------------------------------------------------------------");
    
                    //// Update the value
                    program.UpdateAppSettings(key, "newValue");
                    //// Re-read from config file
                    value = ConfigurationManager.AppSettings[key];
                    Console.WriteLine("New Value read from app.confg for Key = {0} is {1}", key, value);
                }
                else
                {
                    Console.WriteLine("Specified key not found in app.config");
                }
            }
    
            /// 
            /// Updates the app settings.
            /// 
            /// The key.
            /// The value.
            public void UpdateAppSettings(string key, string value)
            {
                Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
                if (configuration.AppSettings.Settings.AllKeys.Contains(key))
                {
                    configuration.AppSettings.Settings[key].Value = value;
                }
    
                configuration.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
    

提交回复
热议问题