Edit

Share via


AppSettingsReader.GetValue(String, Type) Method

Definition

Gets the value for a specified key from the AppSettings property and returns an object of the specified type containing the value from the configuration.

public object GetValue(string key, Type type);

Parameters

key
String

The key for which to get the value.

type
Type

The type of the object to return.

Returns

The value of the specified key.

Exceptions

key is null.

-or-

type is null.

key does not exist in the <appSettings> configuration section.

-or-

The value in the <appSettings> configuration section for key is not of type type.

Examples

The following example shows how to use the GetValue method to retrieve the value for each key in the <appSettings> section of the configuration file.

static void DisplayAppSettings()
{
    try
    {
        var reader = new AppSettingsReader();

        NameValueCollection appSettings = ConfigurationManager.AppSettings;

        for (int i = 0; i < appSettings.Count; i++)
        {
            string key = appSettings.GetKey(i);
            string value = (string)reader.GetValue(key, typeof(string));
            Console.WriteLine("Key : {0} Value: {1}", key, value);
        }
    }
    catch (ConfigurationErrorsException e)
    {
        Console.WriteLine("[DisplayAppSettings: {0}]", e.ToString());
    }
}

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided), 10 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

See also