bit*_*cle 140 c# configurationmanager appsettings
如何检查应用程序设置是否可用?
即app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="someKey" value="someValue"/>
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
并在代码文件中
if (ConfigurationManager.AppSettings.ContainsKey("someKey"))
{
// Do Something
}else{
// Do Something Else
}
Run Code Online (Sandbox Code Playgroud)
小智 213
MSDN:Configuration Manager.AppSettings
if (ConfigurationManager.AppSettings[name] != null)
{
// Now do your magic..
}
Run Code Online (Sandbox Code Playgroud)
要么
string s = ConfigurationManager.AppSettings["myKey"];
if (!String.IsNullOrEmpty(s))
{
// Key exists
}
else
{
// Key doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
Div*_*tel 74
if (ConfigurationManager.AppSettings.AllKeys.Contains("myKey"))
{
// Key exists
}
else
{
// Key doesn't exist
}
Run Code Online (Sandbox Code Playgroud)
通过泛型和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;
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
string LogFileName = ReadAppSetting("LogFile","LogFile");
double DefaultWidth = ReadAppSetting("Width",1280.0);
double DefaultHeight = ReadAppSetting("Height",1024.0);
Color DefaultColor = ReadAppSetting("Color",Colors.Black);
Run Code Online (Sandbox Code Playgroud)