首先,预习一下.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下的设置
1ASP.NET20 自定义配置节学习笔记(一)Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
2ASP.NET20 自定义配置节学习笔记(一)        AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
3ASP.NET20 自定义配置节学习笔记(一)        string list = "";
4ASP.NET20 自定义配置节学习笔记(一)        string[] appKeys = appSection.Settings.AllKeys;
5ASP.NET20 自定义配置节学习笔记(一)        for(int i=0;i<appSection.Settings.Count;i++)
6 list;
删除或更改某一项设置
 1ASP.NET20 自定义配置节学习笔记(一) Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
 2ASP.NET20 自定义配置节学习笔记(一)        AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
 3ASP.NET20 自定义配置节学习笔记(一)        try
 4        }
--------在修改和删除时,特别需要注意 config.Save(),不加上这一句将无效果。
----读取或修改ConnectionStrings的方法道理、方法均一致。

相关文章:

  • 2022-12-23
  • 2022-02-06
  • 2021-07-11
  • 2022-01-13
  • 2021-12-08
  • 2021-07-14
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-05-16
  • 2022-12-23
  • 2021-05-18
相关资源
相似解决方案