Reading AppSettings from ConfigurationManager in .NET 2.0 and later

suggest change

The ConfigurationManager class supports the AppSettings property, which allows you to continue reading settings from the appSettings section of a configuration file the same way as .NET 1.x supported.

app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="keyName" value="anything, as a string"/>
    <add key="keyNames" value="123"/>
    <add key="keyNames" value="234"/>
  </appSettings>
</configuration>
using System;
using System.Configuration;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            string keyValue = ConfigurationManager.AppSettings["keyName"];
            Debug.Assert("anything, as a string".Equals(keyValue));

            var twoKeys = ConfigurationManager.AppSettings["keyNames"];
            Debug.Assert("234".Equals(twoKeys));

            Console.ReadKey();
        }
    }
}

When the same key appears more than once, AppSettings returns the last value. That is why keyNames is "234". ConfigurationManager is in the System.Configuration assembly, which is not referenced by every project template.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents