C#Properties.Settings.Default

C#Properties.Settings.Default,c#,C#,如何确保存在从Properties.Settings.Default检索值? 例如,当我使用此代码时: folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"]; 并且valueSelectedPath不存在,我得到以下异常: 中发生System.Configuration.SettingsPropertyNotFoundException System.dll 如何避免此异常

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

folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
并且value
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
 }
试试这个:(我们的朋友Mike Dinescu提到了这一点,但没有任何细节——编辑:他现在已经提供了细节)

我希望这个解决方案能解决您的问题:)

编辑:或不使用try-catch:

if(!String.IsNullOrEmpty((string)Properties.Settings.Default["SelectedPath"]))
{
   folderBrowserDialog1.SelectedPath = 
         (string)Properties.Settings.Default["SelectedPath"]
}

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

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

您可以为变量设置默认值
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;
    }
} 

我看到了这个问题,但我不明白如何使用“CommonSettings.Default.ContainsKey(str)”。如何获得CommonSettings?不太清楚为什么要编写这样的代码。使用Properties.Settings.Default.SelectedPath,编译器将告诉您错误。这就是使用设置设计器的目的。谢谢。我想在运行时做所有的事情,就像我早期使用注册表一样。但是,我似乎没有其他的方法,除了使用设置设计器谢谢你,但是有没有办法不使用try。。。catch(System.Configuration.SettingsPropertyNotFoundException e)?虽然下面所示的方法有效,但它会以异常为代价。OTOH,上面显示的方法避免引发异常。
[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)