<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!--圖片存放路徑-->
<add key="ImgPath" value="D:\img\" />
</appSettings>
</configuration>
可以看出,app.config和web.config一樣,嗯,它也是一個XML文件。那怎么對這個文件中的元素進行讀取操作呢?很簡單,來看代碼:
string strPath = System.Configuration.ConfigurationSettings.AppSettings["ImgPath"].ToString();
這樣就可以把app.config文件中ImgPath這個元素的Value值讀取出來了。那怎么改寫元素的值呢?如果你認為像讀那樣的去寫,像這樣的代碼:
System.Configuration.ConfigurationSettings.AppSettings["ImgPath"] = @"E:\img\"; //這樣寫是沒用的
在對app.config文件的元素Value值進行修改操作時,只能把app.config文件當作一個普通的XML文件來對待,利用System.Xml.XmlDocument類把這個app.config文件讀到內存中,並通過System.Xml.XmlNode類找到appSettings節點,通過System.Xml.XmlElement類找到節點下的某個元素,利用SetAttribute方法來修改這個元素的值后,最后再將app.config文件保存到原的目錄中,這樣,才算完成了對一個元素Value值的修改操作。下面這個方法可完成對app.config文件appSettings節點下任意一個元素進行修改,當然,你也可能修改這個方法,達到修改任意節點,任意元素的Value值。
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");
}
