/// <summary>
/// 操作Xml的AppSettings
/// </summary>
/// <param name="webConfigPath"></param>
/// <param name="AppsettingsAddKey"></param>
/// <param name="KeyValue"></param>
/// <returns></returns>
public static bool AppSettingsEdit(string webConfigPath, string AppsettingsAddKey, string KeyValue)
{
try
{
string path = System.Web.HttpContext.Current.Server.MapPath(webConfigPath + "/web.config");
XmlDocument xd = new XmlDocument();
xd.Load(path);
//如果没有appsetting,则添加
if (xd.SelectNodes("//appSettings").Count == 0)
{
xd.DocumentElement.AppendChild(xd.CreateElement("appSettings"));
}
//判断节点是否存在,如果存在则修改当前节点
bool addnode = true;
foreach (XmlNode xn1 in xd.SelectNodes("/configuration/appSettings/add"))
{
if (xn1.Attributes["key"].Value == AppsettingsAddKey)
{
addnode = false;
xn1.Attributes["value"].Value = KeyValue;
// xn1.parentnode.removechild(xn1);
break;
}
}
//当前节点不存在,则添加新节点
if (addnode)
{
//创建新节点
XmlNode xn2 = xd.CreateElement("add");
//添加key
XmlAttribute xa = xd.CreateAttribute("key");
xa.Value = AppsettingsAddKey;
xn2.Attributes.Append(xa);
//添加value
xa = xd.CreateAttribute("value");
xa.Value = KeyValue;
xn2.Attributes.Append(xa);
xd.SelectSingleNode("/configuration/appSettings").AppendChild(xn2);
}
//保存web.config
xd.Save(path);
return true;
}
catch
{
return false;
}