Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read AppSettings from app.config in WinForms

Tags:

c#

app-config

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 ?

like image 303
John Ryann Avatar asked Oct 04 '12 16:10

John Ryann


People also ask

How read data from web config file in C#?

Read Key value from WebConfig using C# string constring = ConfigurationManager. ConnectionStrings["ABCD"]. ConnectionString; using (SqlConnection con = new SqlConnection(constring)) { //do database operations like read table data or save data. }


1 Answers

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.

like image 74
Gromer Avatar answered Sep 23 '22 09:09

Gromer