C#修改App.Config文件,

时间:2017-05-15 07:48:42

标签: c#

如何修改App.config文件..! 我能够修改内存中的键值。我需要修改它到文件..?有可能吗?

private string UpdateSetting(string key, string value)
        {
            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings.Add(key, value);
            configuration.Save();
            ConfigurationManager.RefreshSection("appSettings");
            return null;
        }

这将改变内存中键的值,我可以将其修改为文件吗?

1 个答案:

答案 0 :(得分:2)

你的问题在这一行:

configuration.Save();

你应该使用

configuration.Save(ConfigurationSaveMode.Modified);

这是我自己的使用配置的类:

public class SettingsManager
{

    public static string ReadSetting(string key)
    {
        try
        {
            var appSettings = ConfigurationManager.AppSettings;
            var result = appSettings[key] ?? string.Empty;
            return result;
        }
        catch (ConfigurationErrorsException exc)
        {
            //Logger.WriteLog(exc.Message, LoggingLevel.Error);
        }
        return string.Empty;
    }

    public static void AddUpdateAppSettings(string key, string value)
    {
        try
        {
             var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
             var settings = configFile.AppSettings.Settings;
             if (settings.Count == 0 | settings[key] == null)
             {
                  settings.Add(key, value);
             }
             else
             {
                  settings[key].Value = value;
             }
             configFile.Save(ConfigurationSaveMode.Modified);             
             ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
        }
        catch (ConfigurationErrorsException exc)
        {
            //Logger.WriteLog(exc.Message, LoggingLevel.Error);
        }
    }
}