[dotNET]如何利用ConfigurationSettings.AppSettings.GetValues读取配置文件中多个同Key的value

编写者:郑昀@Ultrapower

默认情况下,

string[] strArray = System.Configuration.ConfigurationSettings.AppSettings.GetValues("Uri");

是无法读取配置文件中多个同Key的value的。如下所示的配置:

1<appsettings>
2<add key="Uri" value="uri1"></add>
3<add key="Uri" value="uri2"></add>
4<add key="Uri" value="uri3"></add>
5</appsettings>

用MSDN告诉我们的GetValues是读不到的,只能读到最后一个value。

http://www.codeproject.com/dotnet/namevaluemultiple.asp 告诉我们,

只有这么做才可以:

第一步:

单独建立一个类库MultipleSectionHandler,把NameValueMultipleSectionHandler.cs加进去,并将MultipleSectionHandler.csproj加入到我们的工程中;

第二步:

编译MultipleSectionHandler,生成MultipleSectionHandler.dll;

第三步:

将WebApp应用的Web.config文件中加入

1<configsections>
2<remove name="appSettings"></remove>
3<section name="appSettings" type="MyCompany.Configuration.NameValueMultipleSectionHandler, MultipleSectionHandler"></section>
4</configsections>

表明对于appSettings的读取将采用我们自己的MultipleSectionHandler处理。

第四步:

这时候就可以针对Web.config中的:

1<appsettings>
2<add key="Uri" value="uri1"></add>
3<add key="Uri" value="uri2"></add>
4<add key="Uri" value="uri3"></add>
5</appsettings>

通过

string[] strArray = System.Configuration.ConfigurationSettings.AppSettings.GetValues("Uri");

来读取了 。

Published At
Categories with Web编程
Tagged with
comments powered by Disqus