C # Properties.Settings.Default

How to guarantee that getting a value from Properties.Settings.Defaultexists? For example, when I use this code:

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

and the value SelectedPathdoes not exist, I get a followng exception:

System.Configuration.SettingsPropertyNotFoundException 'occurred in System.dll

How can I avoid this exception?

+4
source share
3 answers

If this collection does not provide a method for checking for the presence of this key, you will have to wrap the code in a block try..catch.

 try{
     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
 }catch(System.Configuration.SettingsPropertyNotFoundException)
 {
     folderBrowserDialog1.SelectedPath = "";  // or whatever is appropriate in your case
 }

If the property Defaultimplements an interface IDictionary, you can use the method ContainsKeyto verify that the given key exists before trying to access it, for example:

 if(Properties.Settings.Default.ContainsKey("SelectedPath"))
 {
     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
 }else{
     folderBrowserDialog1.SelectedPath = ""; // or whatever else is appropriate in your case
 }
+1

:

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

: ( " " , - Edit: )

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
}

I hope this solution solves your problem :)

Edit: or without using try catch:

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

All Articles