C# 配置檔案讀取與修改
配置檔案在很多情況下都使用到, 配置檔案分為兩種 一種是應用程式的配置檔案, 一種是web的配置檔案.
兩種配置檔案最大的差別是web的配置檔案更新之後會實時更新, 應用程式的配置檔案不會實時更新.
更新應用程式的配置檔案之後需重新整理
ConfigurationSettings也存在這個問題, 但是我還不知道怎麼重新整理節點, 呵呵.
舊方法: 各位看官最好使用下面”新方法”
配置檔案:
<configuration>
<appSettings>
<add key="name" value="我是遠端伺服器"/>
</appSettings>
</configuration>
背景程式值得讀取:
string s=System.Configuration.ConfigurationSettings.AppSettings["name"];
修改配置檔案的值:
/// <summary>
/// 更新配置檔案資訊
/// </summary>
/// <param name="name">配置檔案字段名稱</param>
/// <param name="Xvalue">值</param>
private void UpdateConfig(string name,string Xvalue)
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.ExecutablePath + ".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='"+name+"']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value", Xvalue);
doc.Save(Application.ExecutablePath + ".config");
}
向配置檔案插入值:
///<summary>
///向.config檔案的appKey結寫入資訊AppValue 儲存設定
///</summary>
///<param name="AppKey">節點名</param>
///<param name="AppValue">值</param>
Private 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”);
新方法:
System.Configuration.ConfigurationSettings.AppSettings["Key"];
但是現在FrameWork2.0已經明确表示此屬性已經過時。并建議改為ConfigurationManager或WebConfigurationManager。并且AppSettings屬性是隻讀的,并不支援修改屬性值.
但是要想調用ConfigurationManager必須要先在工程裡添加system.configuration.dll程式集的引用。(在解決方案管理器中右鍵點選工程名稱,在右鍵菜單中選擇添加引用,.net TablePage下即可找到)添加引用後可以用 String str = ConfigurationManager.AppSettings["Key"]來擷取對應的值了。
更新配置檔案:
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//添加
cfa.AppSettings.Settings.Add("key", "Name")
//修改
cfa.AppSettings.Settings["BrowseDir"].Value = "name";
最後調用
cfa.Save();
目前的配置檔案更新成功。
ConfigurationManager.RefreshSection("appSettings");// 重新整理命名節,在下次檢索它時将從磁盤重新讀取它。記住應用程式要重新整理節點