C#讀寫app.config中的數據

十月 8, 2010 by
Filed under: CCSP 

讀語句:

  String str = ConfigurationManager.AppSettings[“DemoKey"];

  寫語句:

  Configuration cfa =

  ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

  cfa.AppSettings.Settings[“DemoKey"].Value = “DemoValue";

  cfa.Save();

  配置文件內容格式:(app.config)

  <?xml version="1.0″ encoding="utf-8″ ?>

  <configuration>

  <appSettings>

  <add key="DemoKey" value="*" />

  </appSettings>

  </configuration>

  紅筆標明的幾個關鍵節是必須的

  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();

  當前的配置文件更新成功。

 

  讀寫配置文件app.config

  在.Net中提供了配置文件,讓我們可以很方面的處理配置信息,這個配置是XML格式的。而且.Net中已經提供了壹些訪問這個文件的功能。

  1、讀取配置信息

  下面是壹個配置文件的具體內容:

  <?xml version="1.0″ encoding="utf-8″?>

  <configuration>

  <appSettings>

  <add key="ConnenctionString" value="*" />

  <add key="TmpPath" value="C:\Temp" />

  </appSettings>

  </configuration>

  .net提供了可以直接訪問<appsettings>(註意大小寫)元素的方法,在這元素中有很多的子元素,這些子元素名稱都是 “add”,有兩個屬性分別是“key”和“value”。壹般情況下我們可以將自己的配置信息寫在這個區域中,通過下面的方式進行訪問:

  string ConString=System.Configuration

  .ConfigurationSettings.AppSettings[“ConnenctionString"];

  在appsettings後面的是子元素的key屬性的值,例如appsettings[“connenctionstring"],我們就是訪 問<add key="ConnenctionString" value="*" />這個子元素,它的返回值就是“*”,即value屬性的值。

  2、設置配置信息

  如果配置信息是靜態的,我們可以手工配置,要註意格式。如果配置信息是動態的,就需要我們寫程序來實現。在.Net中沒有寫配置文件的功能,我們可以使用操作XML文件的方式來操作配置文件。下面就是壹個寫配置文件的例子。

  private void SaveConfig(string ConnenctionString)

  {

  XmlDocument doc=new XmlDocument();

  //獲得配置文件的全路徑

  string strFileName=AppDomain.CurrentDomain.BaseDirectory.ToString()

  +"Code.exe.config";

  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=="ConnectionString")

  {

  //對目標元素中的第二個屬性賦值

  att=nodes[i].Attributes[“value"];

  att.Value=ConnenctionString;

  break;

  }

  }

  //保存上面的修改

  doc.Save(strFileName);

  }

Comments

Tell me what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!





*