【轉】C#讀寫配置文件


用C#寫了個windows服務程序,更改exe.config后,必須重新啟動服務才能讀取到新的配置值,如何使配置文件實時生效?

在代碼中讀取配置項值之前:

decimal.TryParse(System.Configuration.ConfigurationManager.AppSettings["StartHour"], out StartForbidHour);

System.Configuration.ConfigurationManager.RefreshSection("appSettings");

使得直接從磁盤讀取,獲得新值。

 

【轉載】C#讀寫配置文件

http://blog.csdn.net/lanman/article/details/5287717

讀配置很簡單,可以用ConfigurationManager.AppSettings[key] 來讀出,

可是寫配置文件時,如果寫成這樣

ConfigurationManager.AppSettings[key] = "111";

總是提示只讀,那么該怎么辦呢?

 

[c-sharp] view plain copy print ?
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Text; 
  4. using System.Configuration; 
  5.  
  6. namespace BQKJ.Common 
  7.     /// <summary> 
  8.     /// 對exe.Config文件中的appSettings段進行讀寫配置操作 
  9.     /// 注意:調試時,寫操作將寫在vhost.exe.config文件中 
  10.     /// </summary> 
  11.     publicclass ConfigAppSettings 
  12.     { 
  13.         /// <summary> 
  14.         /// 寫入值 
  15.         /// </summary> 
  16.         /// <param name="key"></param> 
  17.         /// <param name="value"></param> 
  18.         publicstaticvoid SetValue(string key, string value) 
  19.         { 
  20.             //增加的內容寫在appSettings段下 <add key="RegCode" value="0"/> 
  21.             System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
  22.             if (config.AppSettings.Settings[key] == null
  23.             { 
  24.                 config.AppSettings.Settings.Add(key, value); 
  25.             } 
  26.             else 
  27.             { 
  28.                 config.AppSettings.Settings[key].Value = value; 
  29.             } 
  30.             config.Save(ConfigurationSaveMode.Modified); 
  31.             ConfigurationManager.RefreshSection("appSettings");//重新加載新的配置文件  
  32.         } 
  33.  
  34.         /// <summary> 
  35.         /// 讀取指定key的值 
  36.         /// </summary> 
  37.         /// <param name="key"></param> 
  38.         /// <returns></returns> 
  39.         publicstaticstring GetValue(string key) 
  40.         {  
  41.             System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
  42.             if (config.AppSettings.Settings[key] == null
  43.                 return""
  44.             else 
  45.                 return config.AppSettings.Settings[key].Value; 
  46.         } 
  47.  
  48.     } 

 

 

其實也很簡單,用這兩個封裝過的方法就可以了。

需要注意的是,在IDE調試時,寫入的配置文件其實是寫在了.vshost.exe.config文件中,所以你在.exe.config中是看不到的。只有直接運行exe文件時,才會正確寫入到.exe.config中。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM