C#属性。设置。默认

问题描述 投票:4回答:4

如何确保从Properties.Settings.Default检索值存在?例如,当我使用此代码时:

folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];

并且值SelectedPath不存在,我得到以下异常:

System.Configuration.SettingsPropertyNotFoundException'在System.dll

如何避免这种异常?

c#
4个回答
2
投票

除非该集合提供了一种检查给定键是否存在的方法,否则您将不得不将代码包装在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
 }

4
投票

这里是一种检查密钥是否存在的方法:

    public static bool PropertiesHasKey(string key)
    {
        foreach (SettingsProperty sp in Properties.Settings.Default.Properties)
        {
            if (sp.Name == key)
            {
                return true;
            }
        }
        return false;
    }

0
投票

尝试:(我们的朋友'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"]
}

0
投票

您可以为变量设置默认的null值。将此代码添加到Settings.Designer.cs文件中:

© www.soinside.com 2019 - 2024. All rights reserved.