C#讀取配置文件淺析
C#讀取配置文件是如何實(shí)現(xiàn)的呢?在.Net中提供了配置文件,讓我們可以很方面的處理配置信息,這個(gè)配置是XML格式的。而且.Net中已經(jīng)提供了一些訪問這個(gè)文件的功能。
C#讀取配置文件1、讀取配置信息
下面是一個(gè)配置文件的具體內(nèi)容:
"coal" value="一二三" /> "inWellTime" value="5" />
.Net提供了可以直接訪問(注意大小寫)元素的方法,在這元素中有很多的子元素,這些子元素名稱都是“add”,有兩個(gè)屬性分別是“key”和“value”。一般情況下我們可以將自己的配置信息寫在這個(gè)區(qū)域中,通過下面的方式進(jìn)行訪問:
- String ConString=System.Configuration.ConfigurationSettings.AppSettings["inWellTime"];
在AppSettings后面的是子元素的key屬性的值,例如AppSettings["inWellTime"],我們就是訪問這個(gè)子元素,它的返回值就是“5”,即value屬性的值。
C#讀取配置文件2、設(shè)置配置信息
如果配置信息是靜態(tài)的,我們可以手工配置,要注意格式。如果配置信息是動(dòng)態(tài)的,就需要我們寫程序來實(shí)現(xiàn)。在.Net中沒有寫配置文件的功能,我們可以使用操作XML文件的方式來操作配置文件。
寫了個(gè)WinForm中讀寫配置文件App.config的類
C#讀取配置文件代碼如下:
- 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: 在此處添加構(gòu)造函數(shù)邏輯
- //
- }
- 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 {
- //獲得將當(dāng)前元素的key屬性
- XmlAttribute att=nodes[i].Attributes["key"];
- //根據(jù)元素的***個(gè)屬性來判斷當(dāng)前的元素是不是目標(biāo)元素
- if (att.Value== ""+configKey+"")
- {
- //對(duì)目標(biāo)元素中的第二個(gè)屬性賦值
- att=nodes[i].Attributes["value"];
- att.Value=configValue;
- break;
- }
- }
- //保存上面的修改
- doc.Save(strFileName);
- }
- }
- }
C#讀取配置文件應(yīng)用如下:
C#讀取配置文件之讀?。?/P>
- ConfigClass config = new ConfigClass();
- string coal = config.ReadConfig("coal");
- this.tbOpenFile.Text = config.ReadConfig("inWellTime");
C#讀取配置文件之寫:
- ConfigClass config = new ConfigClass();
- //得到程序的config名:DataOperate.exe.config;
- config.SetConfigName("DataOperate.exe.config");
- config.SaveConfig("coal","三二一");
- config.SaveConfig("inWellTime","10");
注意:當(dāng)修改完App.config。文件后,程序中用到的App.config文件的“key”對(duì)應(yīng)的“value”值需要重讀,否則修改后修改并不能立即起作用,而要等下次程序重啟后才可以讀取到修改后的App.config屬性值。
C#讀取配置文件的相關(guān)內(nèi)容就向你介紹到這里,希望對(duì)你學(xué)習(xí)C#讀取配置文件有所幫助。
【編輯推薦】