C#中動態讀寫App.config配置檔案
在.Net中提供了配置檔案,讓我們可以很方面的處理配置資訊,這個配置是XML格式的。而且.Net中已經提供了一些訪問這個檔案的功能。
1、讀取配置資訊
下面是一個配置檔案的具體內容:
<!-- 此處顯示使用者應用程式和配置的屬性設定。-->
<!-- 示例: -->
<add key="coal" value="一二三" />
<add key="inWellTime" value="5" />
.Net提供了可以直接訪問(注意大小寫)元素的方法,在這元素中有很多的子元素,這些子元素名稱都是“add”,有兩個屬性分別是“key”和“value”。一般情況下我們可以將自己的配置資訊寫在這個區域中,通過下面的方式進行訪問:
String ConString=System.Configuration.ConfigurationSettings.AppSettings["inWellTime"];
在AppSettings後面的是子元素的key屬性的值,例如AppSettings["inWellTime"],我們就是訪問這個子元素,它的返回值就是“5”,即value屬性的值。
2、設定配置資訊
如果配置資訊是靜態的,我們可以手工配置,要注意格式。如果配置資訊是動態的,就需要我們寫程式來實現。在.Net中沒有寫配置檔案的功能,我們可以使用操作XML檔案的方式來操作配置檔案。
寫了個WinForm中讀寫配置檔案App.config的類
程式碼如下:
using System;
using System.Configuration;
using System.Xml;
using System.Data;
namespace cn.zhm.common
{
///
/// ConfigClass 的摘要說明。
///
public class ConfigClass
{
public string strFileName;
public string configName;
public string configValue;
public ConfigClass()
{
//
// TODO: 在此處新增建構函式邏輯
//
}
public string ReadConfig(string configKey)
{
configValue = "";
configValue = ConfigurationSettings.AppSettings[""+configKey+""];
return configValue;
}
//得到程式的config檔案的名稱以及其所在的全路徑
public void SetConfigName(string strConfigName)
{
configName = strConfigName;
//獲得配置檔案的全路徑
GetFullPath();
}
public void GetFullPath()
{
//獲得配置檔案的全路徑
strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()+configName;
}
public void SaveConfig(string configKey,string configValue)
{
XmlDocument doc=new XmlDocument();
doc.Load(strFileName);
//找出名稱為“add”的所有元素
XmlNodeList nodes=doc.GetElementsByTagName("add");
for(int i=0;i<nodes.Count;i++
{
//獲得將當前元素的key屬性
XmlAttribute att=nodes[i].Attributes["key"];
//根據元素的第一個屬性來判斷當前的元素是不是目標元素
if (att.Value== ""+configKey+"")
{
//對目標元素中的第二個屬性賦值
att=nodes[i].Attributes["value"];
att.Value=configValue;
break;
}
}
//儲存上面的修改
doc.Save(strFileName);
}
}
}
應用如下:
讀取:
ConfigClass config = new ConfigClass();
string coal = config.ReadConfig("coal");
this.tbOpenFile.Text = config.ReadConfig("inWellTime");
寫:
ConfigClass config = new ConfigClass();
//得到程式的config名:DataOperate.exe.config;
config.SetConfigName("DataOperate.exe.config");
config.SaveConfig("coal","三二一");
config.SaveConfig("inWellTime","10");
注意:當修改完App.config。檔案後,程式中用到的App.config檔案的“key”對應的“value”值需要重讀,否則修改後修改並不能立即起作用,而要等下次程式重啟後才可以讀取到修改後的App.config屬性值。
同時,winform讀取app.config.可能會出現配置檔案錯誤。修改如下:
<configuration>
<appSettings>
<add key="ConnectionString" value="server=127.0.0.1;uid=sa;pwd=xx;database=test"/>
</appSettings>
</configuration>
另外,修改的只需改app.config就可。編譯時,會自動copy到相應exe目錄下的config。