天天看點

c# winform app.config xml 配置檔案 讀寫操作

/// <summary>

/// 設定配置檔案 對指定項設定指定值

/// </summary>

/// <param name="AppKey"></param>

/// <param name="AppValue"></param>

public static void SetValue(string AppKey, string AppValue)

{

System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();

xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

System.Xml.XmlNode xNode;

System.Xml.XmlElement xElem1;

System.Xml.XmlElement xElem2;

xNode = xDoc.SelectSingleNode("//appSettings");

xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");

if (xElem1 != null) xElem1.SetAttribute("value", AppValue);

else

{

xElem2 = xDoc.CreateElement("add");

xElem2.SetAttribute("key", AppKey);

xElem2.SetAttribute("value", AppValue);

xNode.AppendChild(xElem2);

}

xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");

}

//加載配置資訊

string url = System.Configuration.ConfigurationSettings.AppSettings["url"].ToString();