ASP.NET20 自訂配置節學習筆記(一)

來源:互聯網
上載者:User
首先,預習一下.NET20讀取設定檔(web.config)的方法。
-----
.NET20讀取設定檔的類是WebConfigurationMananger類。
以下通過讀取appSettings和connectionStrings節來預習。
/×備忘:
 <appSettings>
  <add key="***" value="***" />
</appSettings>
<connectionStrings>
   <add name="***" connectionString="***" providerName="***" />
</connectionStrings>
×/
讀取這兩個節點有直接的API:
WebConfigurationManager.AppSettings["節點KEY"]
WebConfigurationMananger.ConnectionStrings["節點名"].ConnectionString;
-----
下面通過GetSection()方法來實現。
實現之前需要瞭解一下相關的類
appSettings對應AppSettingsSection類,其中下有個Settings屬性返回的是KeyValue集合,分別對應 key 和value
而connectionStrings對應ConnectionStringsSection類,其下有個ConnectionStrings屬性,返回的是ConnectionStringSettingsCollection
而ConnectionStringSettings類下有Name、ConnectionString、ProviderName屬性,分別對應相應的設定。
----
迴圈讀取appSettings下的設定1Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
2        AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
3        string list = "";
4        string[] appKeys = appSection.Settings.AllKeys;
5        for(int i=0;i<appSection.Settings.Count;i++)
6        {
7            list += "<br />鍵:" + appKeys[i] + ",值:" + appSection.Settings[appKeys[i]].Value + "<br />";
8        }
9        readAppSettingsResult.Text = list;

刪除或更改某一項設定 1 Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
 2        AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
 3        try
 4        {
 5            appSection.Settings.Remove("testadd");
 6//            appSection.Settings["testadd"].Value="testabc";  修改值
 7            config.Save(); //要記得Save
 8            removeAppSettingResult.Text = "刪除成功";
 9        }
10        catch (System.Exception ee)
11        {
12            removeAppSettingResult.Text = "刪除失敗";
13        }

--------在修改和刪除時,特別需要注意 config.Save(),不加上這一句將無效果。
----讀取或修改ConnectionStrings的方法道理、方法均一致。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.