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