用下面的方法可以操作應用程式檔案夾下的設定檔:
在winform中使用程式讀取和修改App.config裡面的appSettings當中的Value值
這裡我寫成了兩個方法,以供大家參考!
一,命名空間
using System;
using System.Configuration;
using System.Xml;
二,方法
//讀取Value值
public static string GetConfigString(string key)
{
//
// TODO: 在此處添加建構函式邏輯
//
return ConfigurationSettings.AppSettings[key];
}
//寫操作
public static void SetValue(string AppKey,string AppValue)
{
XmlDocument xDoc = new XmlDocument();
//擷取可執行檔的路徑和名稱
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (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");
}
當Properties.Settings變數的範圍"scope"設定為使用者"user"時,通過上述方式讀寫操作並不是操作 了"test.exe.config"檔案,實際操作的檔案儲存在"C:\Documents and Settings\Administrator\Local Settings\Application Data\"路徑下面(註:Administrator是目前使用者檔案夾),檔案名稱字叫"user.config"。點擊工程Properties頁面 中"設定"選項卡的"同步"按鈕會提示這個路徑。