AppSettingsReader
Provides a method for reading values of a particular type from the configuration.
using System.Collections.Specialized;
using System.Globalization;
namespace System.Configuration
{
public class AppSettingsReader
{
private readonly NameValueCollection _map;
private static readonly Type s_stringType = typeof(string);
private const string NullString = "None";
public AppSettingsReader()
{
_map = ConfigurationManager.AppSettings;
}
public object GetValue(string key, Type type)
{
if (key == null)
throw new ArgumentNullException("key");
if ((object)type == null)
throw new ArgumentNullException("type");
string text = _map[key];
if (text != null) {
if (!(type == s_stringType))
try {
return Convert.ChangeType(text, type, CultureInfo.InvariantCulture);
} catch (Exception) {
string p = (text.Length == 0) ? System.SR.AppSettingsReaderEmptyString : text;
throw new InvalidOperationException(System.SR.Format(System.SR.AppSettingsReaderCantParse, p, key, type));
}
switch (GetNoneNesting(text)) {
case 0:
return text;
case 1:
return null;
default:
return text.Substring(1, text.Length - 2);
}
}
throw new InvalidOperationException(System.SR.Format(System.SR.AppSettingsReaderNoKey, key));
}
private static int GetNoneNesting(string val)
{
int i = 0;
int length = val.Length;
if (length > 1) {
for (; val[i] == '(' && val[length - i - 1] == ')'; i++) {
}
if (i > 0 && string.Compare("None", 0, val, i, length - 2 * i, StringComparison.Ordinal) != 0)
i = 0;
}
return i;
}
}
}