G Wood
G Wood

Reputation: 41

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

Upvotes: 1

Views: 1030

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74287

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.

Upvotes: 1

TGH
TGH

Reputation: 39258

What about something like the following

var appSettings = ConfigurationManager.AppSettings;

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

Upvotes: 0

Related Questions