C# 配置文件讀取與修改


配置文件在很多情況下都使用到, 配置文件分為兩種 一種是應用程序的配置文件, 一種是web的配置文件.

兩種配置文件最大的區別是web的配置文件更新之后會實時更新, 應用程序的配置文件不會實時更新.

更新應用程序的配置文件之后需刷新

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM