How can I read/write app.config settings at runtime without using user settings?

后端 未结 3 1522
长发绾君心
长发绾君心 2020-11-28 09:16

I\'m looking for a way to store application or machine level settings that can be written to at runtime using Application Settings. User settings allow read/write but applic

3条回答
  •  Happy的楠姐
    2020-11-28 09:34

    This is the method which allows you to change entries in the :

        internal static bool SetSetting(string Key, string Value)
        {
            bool result = false;
            try
            {
                System.Configuration.Configuration config =
                  ConfigurationManager.OpenExeConfiguration(
                                       ConfigurationUserLevel.None);
    
                config.AppSettings.Settings.Remove(Key); 
                var kvElem= new KeyValueConfigurationElement(Key, Value);
                config.AppSettings.Settings.Add(kvElem);
    
                // Save the configuration file.
                config.Save(ConfigurationSaveMode.Modified);
    
                // Force a reload of a changed section.
                ConfigurationManager.RefreshSection("appSettings");                
    
                result = true;
            }
            finally
            { }
            return result;
        } // function
    

    Note that I have found it is necessary to refresh the section appSettings after the update.

    The function removes a key before it adds it to avoid double entries. This works also if the key does not previously exist. If there is any error it returns false, on success true. The method to read settings is trivial and just listed for completeness:

        internal static string GetSetting(string Key)
        {
            string result = null;
            try
            {
                result = ConfigurationManager.AppSettings[Key];
            }
            finally
            { }
            return result;
        } // function
    

    Note that I've surrounded it by a try ... finally block to suppress errors. If any errors occur, then GetSetting simply returns null while SetSetting returns false. That makes handling easier, however if you require the exceptions you can still add

            catch (Exception) { throw; }
    

    to throw the exception up to the caller. Or, for debugging you could add:

            #if DEBUG
            catch (Exception ex) { 
                    System.Diagnostics.Debug.WriteLine(ex.ToString()); 
            }
            #endif
    

    Which will show the exception in the Output window of Visual Studio if you have selected the "Debug" configuration, but will continue with the code.


    Note (cross-reference to a similar topic):

    • The applicationSettings section is different, since it distinguishes between "User" and "Application" scope and it supports different datatypes, not just strings. If you want to know how you can handle applicationSettings, you can find it here (on stackoverflow):
      How to access applicationSettings

    • If you are uncertain whether you should use AppSettings or applicationSettings, then read this before you decide it.

    • If you encounter the warning 'ConfigurationSettings.AppSettings' is obsolete, then this hint can help you.

    • If you're using the .NET Core framework, check out this link: AppSettings in .NET Core

提交回复
热议问题