简体   繁体   中英

How do I get a section from my winform app.config?

I have reviewed the answers here, but my issue seems somewhat different than the Null return reported by others.

I am trying to grab a section from the app.config so I can do some processing on each name/value pair. I seem unable to get the colection back from ConfigurationManager due to casting issues.

Using C# and .NET 4.5, I have been trying variations on this theme:

AppSettingsSection sec =
    (AppSettingsSection)ConfigurationManager.GetSection("appSettings");

I first attempted to pull the values back into a generic, and used the expected casting error to define a type for the incoming collection. However, each type I try to use gets the same error, can't cast type abc to abc (same type).

Obviously the problem is between the chair and keyboard, but Google isn't helping. Any ideas?

Here is a snip of the app.config

<add key="TemplatePath" value="c:\temp\templates\"/>
<add key="deployDateToken" value="[deployDate]"/>
<add key="NavigateToFolderToken" value="[NavigateToFolder]"/>
<add key="contactToken" value="[ContactInfo]"/>

You can say something like this:

public static IEnumerable<KeyValuePair<string,string>> EnumerateAppSettings()
{
  return ConfigurationManager
         .AppSettings
         .Cast<string>()
         .Select( key => new KeyValuePair<string,string>( key , ConfigurationManager.AppSettings[key] ) )
         ;
}

...

foreach ( KeyValuePair<string,string> item in EnumerateAppSettings() )
{
   // do something
}

Or even

Dictionary<string,string> appSettings = ConfigurationManager
                                        .AppSettings
                                        .Cast<string>()
                                        .ToDictionary( key => key , key => ConfigurationManager.AppSettings[key] )
                                        ;

Or...simplest of all:

NameValueCollection appSettings = ConfigurationManager.AppSettings ;

If you want to get the actual AppSettingsSection , you'll need to see this answer to the question How to get web.config appSettings as ConfigurationSection not NameValueCollection .

What about something like the following

var appSettings = ConfigurationManager.AppSettings;

foreach (var key in appSettings.AllKeys)
{
    appSettings[key]//do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM