जेनेरिक और LINQ के माध्यम से सुरक्षित रूप से डिफ़ॉल्ट मान लौटाया।
public T ReadAppSetting<T>(string searchKey, T defaultValue, StringComparison compare = StringComparison.Ordinal)
{
if (ConfigurationManager.AppSettings.AllKeys.Any(key => string.Compare(key, searchKey, compare) == 0)) {
try
{ // see if it can be converted.
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null) defaultValue = (T)converter.ConvertFromString(ConfigurationManager.AppSettings.GetValues(searchKey).First());
}
catch { } // nothing to do just return the defaultValue
}
return defaultValue;
}
निम्नानुसार उपयोग किया जाता है:
string LogFileName = ReadAppSetting("LogFile","LogFile");
double DefaultWidth = ReadAppSetting("Width",1280.0);
double DefaultHeight = ReadAppSetting("Height",1024.0);
Color DefaultColor = ReadAppSetting("Color",Colors.Black);
Dim configValue As String = Util.IsNull(ConfigurationManager.AppSettings.Get("SettingName"), String.Empty)