如何获取NameValueSectionHandlertypes的ConfigurationSection的值

我正在使用C#,Framework 3.5(VS 2008)。

我正在使用ConfigurationManager将configuration(不是默认的app.config文件)加载到configuration对象中。

使用configuration类,我能够得到一个ConfigurationSection ,但我找不到方法来获取该部分的值。

在configuration中, ConfigurationSection的types是System.Configuration.NameValueSectionHandler

值得一提的是,当我使用ConfigurationManager的方法GetSection (只在它的默认app.config文件中工作时),我收到了一个对象types,我可以投入到键值对的集合中,而我刚收到像Dictionary一样的价值。 但是,当我从Configuration类接收到ConfigurationSection类时,我无法进行这种转换。

编辑:configuration文件的示例:

 <configuration> <configSections> <section name="MyParams" type="System.Configuration.NameValueSectionHandler" /> </configSections> <MyParams> <add key="FirstParam" value="One"/> <add key="SecondParam" value="Two"/> </MyParams> </configuration> 

在app.config中,我可以使用它的方式的示例(“GetSection”方法仅用于默认的app.config):

 NameValueCollection myParamsCollection = (NameValueCollection)ConfigurationManager.GetSection("MyParams"); Console.WriteLine(myParamsCollection["FirstParam"]); Console.WriteLine(myParamsCollection["SecondParam"]); 

这里有一个很好的post,说明如何做到这一点。

如果要从app.config以外的文件中读取值,则需要将其加载到ConfigurationManager中。

试试这个方法: ConfigurationManager.OpenMappedExeConfiguration()

有一个如何在MSDN文章中使用它的例子。

遇到确切的问题。 问题是因为.config文件中的NameValueSectionHandler。 您应该使用AppSettingsSection:

 <configuration> <configSections> <section name="DEV" type="System.Configuration.AppSettingsSection" /> <section name="TEST" type="System.Configuration.AppSettingsSection" /> </configSections> <TEST> <add key="key" value="value1" /> </TEST> <DEV> <add key="key" value="value2" /> </DEV> </configuration> 

那么在C#代码中:

 AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST"); 

顺便说一句NameValueSectionHandler不再支持2.0。

尝试使用AppSettingsSection而不是NameValueCollection 。 像这样的东西:

 var section = (AppSettingsSection)config.GetSection(sectionName); string results = section.Settings[key].Value; 

资料来源: http : //social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/d5079420-40cb-4255-9b3b-f9a41a1f7ad2/

我能得到这个工作的唯一方法是手动实例化部分处理程序types,将原始XML传递给它,并投射生成的对象。

似乎相当低效,但你去。

我写了一个扩展方法来封装这个:

 public static class ConfigurationSectionExtensions { public static T GetAs<T>(this ConfigurationSection section) { var sectionInformation = section.SectionInformation; var sectionHandlerType = Type.GetType(sectionInformation.Type); if (sectionHandlerType == null) { throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type)); } IConfigurationSectionHandler sectionHandler; try { sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType); } catch (InvalidCastException ex) { throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex); } var rawXml = sectionInformation.GetRawXml(); if (rawXml == null) { return default(T); } var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(rawXml); return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement); } } 

在你的例子中,你会这样称呼它:

 var map = new ExeConfigurationFileMap { ExeConfigFilename = @"c:\\foo.config" }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); var myParamsSection = configuration.GetSection("MyParams"); var myParamsCollection = myParamsSection.GetAs<NameValueCollection>(); 

这是一个古老的问题,但我使用下面的课程来完成这项工作。 它基于Scott Dorman的博客 :

 public class NameValueCollectionConfigurationSection : ConfigurationSection { private const string COLLECTION_PROP_NAME = ""; public IEnumerable<KeyValuePair<string, string>> GetNameValueItems() { foreach ( string key in this.ConfigurationCollection.AllKeys ) { NameValueConfigurationElement confElement = this.ConfigurationCollection[key]; yield return new KeyValuePair<string, string> (confElement.Name, confElement.Value); } } [ConfigurationProperty(COLLECTION_PROP_NAME, IsDefaultCollection = true)] protected NameValueConfigurationCollection ConfCollection { get { return (NameValueConfigurationCollection) base[COLLECTION_PROP_NAME]; } } 

用法很简单:

 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); NameValueCollectionConfigurationSection config = (NameValueCollectionConfigurationSection) configuration.GetSection("MyParams"); NameValueCollection myParamsCollection = new NameValueCollection(); config.GetNameValueItems().ToList().ForEach(kvp => myParamsCollection.Add(kvp)); 

以下是前面提到的这个博客的一些例子:

 <configuration> <Database> <add key="ConnectionString" value="data source=.;initial catalog=NorthWind;integrated security=SSPI"/> </Database> </configuration> 

获取值:

  NameValueCollection db = (NameValueCollection)ConfigurationSettings.GetConfig("Database"); labelConnection2.Text = db["ConnectionString"]; 

另一个例子:

 <Locations ImportDirectory="C:\Import\Inbox" ProcessedDirectory ="C:\Import\Processed" RejectedDirectory ="C:\Import\Rejected" /> 

获得价值:

 Hashtable loc = (Hashtable)ConfigurationSettings.GetConfig("Locations"); labelImport2.Text = loc["ImportDirectory"].ToString(); labelProcessed2.Text = loc["ProcessedDirectory"].ToString();