如何修改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;
}
这将改变内存中键的值,我可以将其修改为文件吗?
答案 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);
}
}
}