如何确保从Properties.Settings.Default
检索值存在?例如,当我使用此代码时:
folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
并且值SelectedPath
不存在,我得到以下异常:
System.Configuration.SettingsPropertyNotFoundException'在System.dll
如何避免这种异常?
除非该集合提供了一种检查给定键是否存在的方法,否则您将不得不将代码包装在try..catch
块中。
try{
folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
}catch(System.Configuration.SettingsPropertyNotFoundException)
{
folderBrowserDialog1.SelectedPath = ""; // or whatever is appropriate in your case
}
如果Default
属性实现了IDictionary
接口,则可以在尝试访问给定密钥之前使用ContainsKey
方法测试给定密钥的存在,例如:
if(Properties.Settings.Default.ContainsKey("SelectedPath"))
{
folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
}else{
folderBrowserDialog1.SelectedPath = ""; // or whatever else is appropriate in your case
}
这里是一种检查密钥是否存在的方法:
public static bool PropertiesHasKey(string key)
{
foreach (SettingsProperty sp in Properties.Settings.Default.Properties)
{
if (sp.Name == key)
{
return true;
}
}
return false;
}
尝试:(我们的朋友'Mike Dinescu'提到没有详细信息-编辑:他现在提供了详细信息)] >>
try { folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"] } catch(System.Configuration.SettingsPropertyNotFoundException e) { MessageBox.Show(e.Message); // or anything you want } catch(Exception e) { //if any exception but above one occurs this part will execute }
我希望此解决方案可以解决您的问题:)
编辑:或不使用try catch:
if(!String.IsNullOrEmpty((string)Properties.Settings.Default["SelectedPath"]))
{
folderBrowserDialog1.SelectedPath =
(string)Properties.Settings.Default["SelectedPath"]
}
您可以为变量设置默认的null
值。将此代码添加到Settings.Designer.cs
文件中: