using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Utilities
{
public class AppConfigHelper
{
public static string GetValueByKey(string key)
{
return ConfigurationManager.AppSettings[key];
}
public static void ModifyAppSettings(string strKey, string value)
{
var doc = new XmlDocument();
var strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
doc.Load(strFileName);
var appSettingsNode = doc.SelectSingleNode("configuration//appSettings");
var nodes = appSettingsNode.ChildNodes;
int i = 0;
for (; i < nodes.Count; i++)
{
var xmlAttributeCollection = nodes[i].Attributes;
if (xmlAttributeCollection != null)
{
var att = xmlAttributeCollection["key"];
if (att == null) continue;
if (att.Value != strKey) continue;
att = xmlAttributeCollection["value"];
att.Value = value;
}
break;
}
if (i >= nodes.Count)
{
XmlElement title = doc.CreateElement("add");
title.SetAttribute("key", strKey);
title.SetAttribute("value", value);
appSettingsNode.AppendChild(title);
}
doc.Save(strFileName);
ConfigurationManager.RefreshSection("appSettings");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="key1" value="value1" />
</appSettings>
</configuration>