John Ryann
John Ryann

Reputation: 2393

How to read AppSettings from app.config in WinForms

I usually use a text file as a config. But this time I would like to utilize app.config to associate a file name (key) with a name (value) and make the names available in combo box

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
   <add key="Scenario1.doc" value="Hybrid1"/>
   <add key="Scenario2.doc" value="Hybrid2"/>
   <add key="Scenario3.doc" value="Hybrid3"/>
</appSettings>
</configuration>

will this work? how to retrieve the data ?

Upvotes: 12

Views: 44525

Answers (2)

Gromer
Gromer

Reputation: 9931

Straight from the docs:

using System.Configuration;

// Get the AppSettings section.        
// This function uses the AppSettings property
// to read the appSettings configuration 
// section.
public static void ReadAppSettings()
{
  try
  {
    // Get the AppSettings section.
    NameValueCollection appSettings = ConfigurationManager.AppSettings;

    // Get the AppSettings section elements.
    Console.WriteLine();
    Console.WriteLine("Using AppSettings property.");
    Console.WriteLine("Application settings:");

    if (appSettings.Count == 0)
    {
      Console.WriteLine("[ReadAppSettings: {0}]",
      "AppSettings is empty Use GetSection command first.");
    }
    for (int i = 0; i < appSettings.Count; i++)
    {
      Console.WriteLine("#{0} Key: {1} Value: {2}",i, appSettings.GetKey(i), appSettings[i]);
    }
  }
  catch (ConfigurationErrorsException e)
  {
    Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
  }
}

So, if you want to access the setting Scenario1.doc, you would do this:

var value = ConfigurationManager.AppSettings["Scenario1.doc"];

Edit:

As Gabriel GM said in the comments, you will have to add a reference to System.Configuration.

Upvotes: 21

Pavan Josyula
Pavan Josyula

Reputation: 1375

app settings in app.config are to store application/environment specific settings not to store data which binds to UI.

If you cant avoid storing in config because of weird business requests I would rather stick to one single setting

<add key="FileDropDown" value="File1-Value|File2-Value" />

and write C# code to get this setting ConfigurationManager.AppSettings["FileDropDown"] and do some string Splits ('|') and ('-') to create kvp collection and bind it to UI.

Upvotes: 0

Related Questions