【问题标题】:.NET ConfigurationManager app.config confusion.NET ConfigurationManager app.config 混淆
【发布时间】:2010-11-19 16:58:51
【问题描述】:

我有一个 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 文件来调试虚拟主机。我知道在发布时它可能被重命名为TestConsole.exe.config。那么出了什么问题呢?是代码错误的情况还是什么?

【问题讨论】:

  • .NET 不会“出错”。它抛出异常。当一个异常未被捕获并导致您的程序“不工作”时,您应该在您的问题中发布完整的异常。捕获异常,然后发布ex.ToString()的结果。
  • 会的。我尝试将文件重命名为 TestConsole.vhost.exe.config 但它返回为空。
  • 嗨,约翰,这是个例外。为 PowershellSnapI ns 创建配置节处理程序时出错:无法加载文件或程序集“系统”或其依赖项之一。该系统找不到指定的文件。 (C:\Users\Administrator\Documents\Visual Studio 2008\Projects\TestConsole\TestConsole\bin\Debug\TestConsole.vshost.exe.config 第 4 行)
  • 我从部分名称中删除了 ,System,现在它显示为
    我现在得到了异常。无法将“System.Configuration.DefaultSection”类型的对象转换为“System.Collections.IDictionary”类型。

标签: c# configuration app-config


【解决方案1】:

我是这样做的:

-确保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 管理单元名称。
  • 嗨,Ngu Soon Hui,它成功了。谢谢。我现在可以看到(后见之明)ConfigurationManager 类是静态的。谢谢。
  • 对我来说与(NameValueCollection) 的演员一起工作。
【解决方案2】:

VS 将 app.config 重命名为 yourappname.exe 并将其与您的 .exe 一起放在 bin 目录中

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

【讨论】:

  • TestConsole.vhost.exe.config 文件位于 Visual Studio 2008\Projects\TestConsole\TestConsole\bin\Debug 目录中。
猜你喜欢
  • 2010-12-02
  • 2010-10-09
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 2019-06-21
  • 2011-03-22
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多