.NET ConfigurationManager app.config混淆

5

我有一个app.config文件,其中包含以下内容

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name ="PowershellSnapIns" type ="System.Configuration.DictionarySectionHandler,System"/>
    </configSections>

    <PowershellSnapIns>
        <add key="SnapIn1" value="WebAdministration" />
        <add key="SnapIn2" value="Jimmy Hendrix" />
        <add key="SnapIn3" value="..." />
    </PowershellSnapIns>
</configuration>

我原本想使用ConfigurationSettings类来读取它,但该类已被弃用。那个类非常简单易用。现在我必须使用ConfigurationManager类,并且我现在有以下代码来读取它。

 System.Configuration.Configuration config =
     ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

IDictionary SnapInList = (IDictionary) config.GetSection("PowershellSnapIns");

但是它一直报错。我更改了app.config的属性以便在构建过程中复制,但它仍然接受找不到文件的事实。异常信息显示它正在寻找TestConsole.vshost.exe.config。vs2k8sp1现在是否自动为您重命名app.config文件?如果是,那么我错在哪里?我肯定不需要将app.config文件重命名为debug vhost。我知道在发布时它可能会被重命名为TestConsole.exe.config。那么出了什么问题吗?是代码有误吗?

2
.NET不会“错误退出”。它会抛出异常。当一个异常未被捕获并导致程序“无法工作”时,您应该在问题中发布完整的异常信息。捕获异常,然后发布ex.ToString()的结果。 - John Saunders
我尝试将文件重命名为TestConsole.vhost.exe.config,但它返回为空。 - scope_creep
你好,John, 这是异常情况。 创建PowershellSnapIns配置节处理程序时出错:无法加载文件或程序集“System”或其某个依赖项。系统找不到指定的文件。(C:\Users\Administrator\Documents\Visual Studio 2008\Projects\TestConsole\TestConsole\bin\Debug\TestConsole.vshost.exe.config第4行) - scope_creep
我从部分名称中删除了“System”,现在它的内容为:<section name ="PowershellSnapIns" type ="System.Configuration.DictionarySectionHandler"/>现在我遇到了异常。无法将类型为'System.Configuration.DefaultSection'的对象强制转换为类型'System.Collections.IDictionary'。 - scope_creep
2个回答

12

这是我完成它的方法:

- 确保 SystemSystem.Configuration.dll 在您的 bin 目录中可用。您可以通过将引用添加到这两个 dll 并设置它们的 copy local 属性为 true 来实现此目的。

- 在您的 App.Config 文件中,确保将 copy local 属性设置为 false

- 使用以下方法:

public static string XMLCheck
{
    get
    {
        var section =(Hashtable)ConfigurationManager.GetSection("PowershellSnapIns");
        return (string)section["SnapIn1"];

    }
}

- XMLCheck 应该返回 "WebAdministration"


关键字并不重要,因为我不需要知道关键字,只需要知道值,即PowerShell Snapin名称。 - scope_creep
嗨,Ngu Soon Hui, 它起作用了。谢谢。我现在可以看到(回想起来真美好),ConfigurationManager类是静态的。谢谢。 - scope_creep
对我来说,使用强制转换(NameValueCollection)可以正常工作。 - David d C e Freitas

1

Visual Studio会将app.config重命名为yourappname.exe并将其与您的.exe文件一起放置在bin目录中。

请确认该文件是否与您的exe文件一起存在于bin目录中。


1
文件TestConsole.vhost.exe.config位于Visual Studio 2008\Projects\TestConsole\TestConsole\bin\Debug目录中。 - scope_creep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接