C#Properties.Settings.Default

时间:2014-11-09 17:35:18

标签: c#

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

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

和值SelectedPath不存在,我得到了以下的例外:

  发生了

System.Configuration.SettingsPropertyNotFoundException'   System.dll中

如何避免此异常?

4 个答案:

答案 0 :(得分:3)

以下是检查密钥是否存在的方法:

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

答案 1 :(得分: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
 }

答案 2 :(得分: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"]
}

答案 3 :(得分:0)

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

[UserScopedSetting]
[DebuggerNonUserCode]
[DefaultSettingValue(null)] // <-- set default value
public string test1
{
    get
    {
        return (string)this[nameof(test1)];
    }
    set
    {
        this[nameof(test1)] = (object)value;
    }
} 

然后检查:

if (Properties.Settings.Default.test1 != null)