2009-08-14 49 views
5

我有一个app.config文件,其中包含以下.NET ConfigurationManager中的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文件来调试vhost。我知道在释放它可能被重命名为TestConsole.exe.config。那么,哪里出了问题?这是代码错误还是什么?

+2

.NET不会“出错”。它抛出异常。当一个异常未被捕获,并导致你的程序“不工作”时,你应该在你的问题中发布完整的异常。捕获异常,然后发布'ex.ToString()'的结果。 – 2009-08-14 16:18:16

+0

会做。我尝试将该文件重命名为TestConsole.vhost.exe.config,但它回来了。 – 2009-08-14 16:26:20

+0

嗨,约翰, 这是个例外。 为PowershellSnapI创建配置节处理程序时发生错误 ns:无法加载文件或程序集“System”或其某个依赖项。系统不能找到指定的文件。 (C:\ Users \ Administrator \ Documents \ Visual Stu dio 2008 \ Projects \ TestConsole \ TestConsole \ bin \ Debug \ TestConsole.vshost.exe.confi g line 4) – 2009-08-14 16:31:45

回答

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"]; 

    } 
} 

-The XMLCheck应该返回 “WebAdministration

+0

这个关键并不重要,因为我不需要知道关键字,只是值,它是powershell snapin的名字。 – 2009-08-14 16:24:59

+0

答复已更新。 – Graviton 2009-08-14 16:42:19

+0

嗨Ngu Soon Hui, 它的工作。谢谢。我现在可以看到(事后看来很美)ConfigurationManager类是静态的。谢谢。 – 2009-08-14 17:23:57

1

VS重命名的app.config到yourappname.exe并将其放置在bin目录与你一起。 exe

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

+1

文件TestConsole.vhost.exe.config位于Visual Studio 2008 \ Projects \ TestConsole \ TestConsole \ bin \ Debug目录中。 – 2009-08-14 16:28:27