.NET ConfigurationManager app.config confusion

我与影子孤独终老i 提交于 2019-12-22 06:37:30

问题


I've got an app.config file, which contains the following

<?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>

I was going to use the ConfigurationSettings class to read it, but that has been deprecated. That was fairly simple to use. Now I have to use the ConfigurationManager class, and I now have this code to read it.

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

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

But it keeps erroring out. I changed the app.config properties to copy across to the build, but it keeps accepting that it can't find the file. The exception says it's looking for TestConsole.vshost.exe.config. Does vs2k8sp1 now rename the app.config for you automatically, and if so, what am I doing wrong? Surely I don't need to rename the app.config file to debug vhost. I do know in release that it's probably being renamed TestConsole.exe.config. So what's going wrong? Is it the case of the code wrong or what?


回答1:


Here's how I did it:

-Make sure that System and System.Configuration.dll are available in your bin directory. You do this by adding the reference to both dlls and set their copy local attribute to true.

-Make sure in your App.Config file, set the copy local attributes to false.

-Use the following method:

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

    }
}

-The XMLCheck should return "WebAdministration"




回答2:


VS renames the app.config to yourappname.exe and places it in the bin directory along with your .exe

Can you confirm that the file exists in the bin directory along with your exe.



来源:https://stackoverflow.com/questions/1278730/net-configurationmanager-app-config-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!