-----
.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;
删除或更改某一项设置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(),不加上这一句将无效果。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 }
----读取或修改ConnectionStrings的方法道理、方法均一致。