程式控制存取 Web.config 應用程式設定檔

| 原始連結

在一般的 Web-base 應用系統中我們總是會用 Web.config 來設定各種環境配置,尤其是在 <appSettings> 區段中可以允許自由的加入自定的 key/value 成對參數,在以往.net 1.0 或是 .net 1.1 之下可以很簡的讀取自定參教,然而如果要在程式中以程式控制來寫入 Web.config 卻不太容易,幸運的是在 .net 2.0 中以已增加了若干種物件來支援這些功能,其中 System.Web.Configuration.WebConfigurationManager 物件就俱有操作 Web.config 檔案的能力。

假設在我們範例中的 Web.config 設定如下:

 
1 <appSettings> 
2   <add key="WebName" value="This is MyWeb" /> 
3   <add key="LastUpdate" value="2006-01-01" /> 
4  </appSettings> 
  看不清楚 | 列印



讀取設定
單純的讀取設定非常的簡單,僅僅只需要一行程式碼
 
1 string str = System.Web.Configuration.WebConfigurationManager.AppSettings["WebName"]; 
  看不清楚 | 列印

這樣我們便可以讀取到 "This is MyWeb" 字串,然後將它運用在程式中任何需要使用的地方。


修改設定
修改設定的步驟稍微多了一點,但是依然非常的簡單
 
1 Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
2  
3 config.AppSettings.Settings["LastUpdate"].Value =  
4 DateTime.Noew.ToString("yyyy-MM-dd"); 
5  
6 config.Save(); 
  看不清楚 | 列印

當程式執行到 config.Save(); 的時後就會將所有更變存儲回 Web.config 裏。


真實的應用
現在要討論的是程式中俱備有存取 Web.config 能力可以用來做些什麼..... 嗯.... 也許在一些小型的系統中可以用來直接當做系統參數的存放檔,那麼我們就不再需要另外的 .ini 檔或是 xml 設定檔了不是嗎?
如果寫一個專門控制的 SysConfig 物件然後存放到 Application 變數裏更能突顯它的好處
 
1 public class SystemConfiguration 
2
3     private string m_WebName= string.Empty; 
4     private DateTime m_LastUpdate= DateTime.Now; 
5  
6     public SystemConfiguration() 
7     { 
8  
9         this.m_WebName = WebConfigurationManager.AppSettings["WebName"]; 
10  
11         this.m_LastUadate = DateTime.Parse(WebConfigurationManager.AppSettings["LastUadate"]); 
12  
13     } 
14  
15     public void SaveConfig 
16     { 
17         Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
18          
19        config.AppSettings.Settings["WebName"].Value = this.m_WebName; 
20        config.AppSettings.Settings["LastUpdate"].Value = this.m_LastUpdate; 
21  
22        config.Save(); 
23  
24     } 
25  
26     public string WebName 
27     { 
28        get 
29         { 
30            return this.m_WebName; 
31         } 
32        set 
33        { 
34             this.m_WebName = value; 
35        } 
36     } 
37  
38     public DateTime LastUadate 
39      { 
40         get 
41          { 
42             return this.m_LastUadate; 
43          } 
44         set 
45         { 
46              this.m_LastUadate= value; 
47         } 
48      } 
49  
50
  看不清楚 | 列印


現在我們有了自定的 SystemConfiguration 物件,剩下的只需要把它加到 Application 中隨時取用。

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 romeogi1023 的頭像
    romeogi1023

    David's Home

    romeogi1023 發表在 痞客邦 留言(0) 人氣()