How to read AppSettings from app.config in WinForms

a 夏天 提交于 2019-12-05 03:42:32
Gromer

Straight from the docs:

using 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.

Pavan Josyula

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.

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