如何获取NameValueSectionHandler类型的ConfigurationSection的值

Lir*_*n B 64 c# configurationmanager config configurationsection

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

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

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

在配置中,ConfigurationSection是类型System.Configuration.NameValueSectionHandler.

对于什么是价值,当我使用的方法GetSectionConfigurationManager(只能当它是对我的默认app.config文件),我收到了一个对象类型,我可以投进去对键值的集合,我刚刚收到像字典一样的价值.但是,当我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>
Run Code Online (Sandbox Code Playgroud)

我在app.config上使用它时的方式示例("GetSection"方法仅适用于默认的app.config):

NameValueCollection myParamsCollection =
             (NameValueCollection)ConfigurationManager.GetSection("MyParams");

Console.WriteLine(myParamsCollection["FirstParam"]);
Console.WriteLine(myParamsCollection["SecondParam"]);
Run Code Online (Sandbox Code Playgroud)

ner*_*jus 22

受到确切问题的影响.问题是因为.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>
Run Code Online (Sandbox Code Playgroud)

然后在C#代码中:

AppSettingsSection section = (AppSettingsSection)ConfigurationManager.GetSection("TEST");
Run Code Online (Sandbox Code Playgroud)

btw 2.0中不再支持NameValueSectionHandler.

  • 转换为AppSettings部分对我没有用.相反,我已经转换为NameValueCollection并且工作了. (8认同)

Mon*_*nch 17

这是一篇很好的文章,展示了如何做到这一点.

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

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

有一个如何在MSDN文章中使用它的示例.

  • 正如我在帖子中所说,这就是我所做的.我收到了Configuraion类,从中我收到了一个ConfigurationSection.我的问题是如何从ConfigurationSection对象中获取值?我没有问如何获取Configuration对象..无论如何,谢谢! (5认同)
  • 顺便说一句,在你给我的例子中,他们没有使用来自OpenMappedExeConfiguration的Configuration类,但他们使用默认的app.config(可以使用.GetSection/.GetConfig方法使用,但正如我所说的那样)我的帖子 - 我已经这样做了.但它对我来说没有好处,因为它只适用于app.config).而对于msdn,我找不到我的问题的答案.. (2认同)
  • 这个答案似乎受到链接腐烂的影响,这就是为什么[仅限链接答案不鼓励](http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really - 良好 - 答案). (2认同)

Ste*_*all 13

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

var section = (AppSettingsSection)config.GetSection(sectionName);
string results = section.Settings[key].Value;
Run Code Online (Sandbox Code Playgroud)

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

  • nope这样你就会得到"无法将'System.Configuration.DefaultSection'类型的对象强制转换为'System.Configuration.AppSettingsSection'." (4认同)
  • @nerijus:来吧男人......当然,史蒂文的一个假设是,你实际上相应地更改了部分的类型......没有冒犯,但你真的可以在评论之前思考.我试过这个解决方案,但它确实有效 史蒂文+1 (4认同)
  • @h9uest:这不是那么简单,因为立然写的部分是`System.Configuration.NameValueSectionHandler`。这个答案似乎更像是一种肮脏的黑客攻击。 (2认同)

Ste*_*eld 8

我能让它工作的唯一方法是手动实例化段处理程序类型,将原始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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您在示例中调用它的方式是:

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>();
Run Code Online (Sandbox Code Playgroud)