C#讀寫app.config中的數據

十月 8, 2010 by · Leave a Comment
Filed under: CCSP 

Warning: Division by zero in /var/www/html/wwwroot/itrenzheng.hk/wp-content/themes/code-blue_20/functions.php on line 16

Warning: Division by zero in /var/www/html/wwwroot/itrenzheng.hk/wp-content/themes/code-blue_20/functions.php on line 16

Warning: Division by zero in /var/www/html/wwwroot/itrenzheng.hk/wp-content/themes/code-blue_20/functions.php on line 16

讀語句:

  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"… Continue reading