Winform操作App.config(增加、修改、删除、读取等)

2017年03月06日 20:13:17

阅读数:5606

1. 操作App.config需要添加引用System.Configuration,并且在程序中using System.Configuration。

2. 添加键为keyName、值为keyValue的项:

 
  1. public void addItem(string keyName, string keyValue)

  2. {

  3. //添加配置文件的项,键为keyName,值为keyValue

  4. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  5. config.AppSettings.Settings.Add(keyName, keyValue);

  6. config.Save(ConfigurationSaveMode.Modified);

  7. ConfigurationManager.RefreshSection("appSettings");

  8. }

3. 判断键为keyName的项是否存在:

 
  1. public bool existItem(string keyName)

  2. {

  3. //判断配置文件中是否存在键为keyName的项

  4. foreach (string key in ConfigurationManager.AppSettings)

  5. {

  6. if (key == keyName)

  7. {

  8. //存在

  9. return true;

  10. }

  11. }

  12. return false;

  13. }

4. 获取键为keyName的项的值:

 
  1. public string valueItem(string keyName)

  2. {

  3. //返回配置文件中键为keyName的项的值

  4. return ConfigurationManager.AppSettings[keyName];

  5. }

5. 修改键为keyName的项的值:

 
  1. public void modifyItem(string keyName, string newKeyValue)

  2. {

  3. //修改配置文件中键为keyName的项的值

  4. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  5. config.AppSettings.Settings[keyName].Value = newKeyValue;

  6. config.Save(ConfigurationSaveMode.Modified);

  7. ConfigurationManager.RefreshSection("appSettings");

  8. }

6. 删除键为keyName的项:

 
  1. public void removeItem(string keyName)

  2. {

  3. //删除配置文件键为keyName的项

  4. Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  5. config.AppSettings.Settings.Remove(keyName);

  6. config.Save(ConfigurationSaveMode.Modified);

  7. ConfigurationManager.RefreshSection("appSettings");

  8. }

猜你喜欢

转载自blog.csdn.net/weixin_42339460/article/details/81200843