從使用System.Configuration.NameValueSectionHandler定義的部分的配置文件獲取值很容易,當您使用當前配置文件應用程序。當使用ConfigurationManager.OpenMappedExeConfiguration時,如何從ConfigSection中獲取值?使用Configuration.OpenMappedExeConfiguration
示例配置文件。
<configuration>
<configSections>
<section name="MyParams" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<MyParams>
<add key="FirstParam" value="One"/>
<add key="SecondParam" value="Two"/>
</MyParams>
</configuration>
示例可輕鬆讀取它的代碼。
NameValueCollection myParamsCollection =
ConfigurationManager.GetSection("MyParams") as NameValueCollection;
這是不起作用的代碼。
NameValueCollection collection =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
.GetSection("MyParams") as NameValueCollection;
失敗,編譯時出現以下錯誤。
無法通過引用轉換,裝箱轉換,取消裝箱轉換,包裝轉換或空類型轉換將類型「System.Configuration.ConfigurationSection」轉換爲「System.Collections.Specialized.NameValueCollection」。
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)返回System.Configuration.Configuration,Configuration.GetSection返回ConfigurationSection。
ConfigurationManager.GetSection返回對象。
那麼,當我必須使用OpenExeConfiguration時,如何取回我的NameValueCollection?
不錯的巫術在這一個......! – granadaCoder