C# 配置文件讀取與修改

 

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");// 刷新命名節,在下次檢索它時將從磁盤重新讀取它。記住應用程序要刷新節點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章