1. 操作App.config需要添加引用System.Configuration,并且在程序中using System.Configuration。
2. 添加键为keyName、值为keyValue的项:
public void addItem(string keyName, string keyValue)
{
//添加配置文件的项,键为keyName,值为keyValue
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Add(keyName, keyValue);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
3. 判断键为keyName的项是否存在:
public bool existItem(string keyName)
{
//判断配置文件中是否存在键为keyName的项
foreach (string key in ConfigurationManager.AppSettings)
{
if (key == keyName)
{
//存在
return true;
}
}
return false;
}
4. 获取键为keyName的项的值:
public string valueItem(string keyName)
{
//返回配置文件中键为keyName的项的值
return ConfigurationManager.AppSettings[keyName];
}
5. 修改键为keyName的项的值:
public void modifyItem(string keyName, string newKeyValue)
{
//修改配置文件中键为keyName的项的值
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[keyName].Value = newKeyValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
6. 删除键为keyName的项:
public void removeItem(string keyName)
{
//删除配置文件键为keyName的项
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(keyName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}