ConfigurationManager.AppSettings - How to modify and save?

后端 未结 9 1505
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 05:10

It might sound too trival to ask and I do the same thing as suggested in articles, yet it doesn\'t work as expected. Hope someone can point me to the right direction.

<
9条回答
  •  北海茫月
    2020-11-28 05:56

    I know I'm late :) But this how i do it:

    public static void AddOrUpdateAppSettings(string key, string value)
    {
        try
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;
            if (settings[key] == null)
            {
                settings.Add(key, value);
            }
            else
            {
                settings[key].Value = value;
            }
            configFile.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException)
        {
            Console.WriteLine("Error writing app settings");
        }
    }
    

    For more information look at MSDN

提交回复
热议问题