Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Properties.Settings.Default

Tags:

c#

How to ensure that retrieving value from Properties.Settings.Default exists? For example, when I use this code:

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

and value SelectedPath does not exist, I get the followng exception:

System.Configuration.SettingsPropertyNotFoundException' occurred in System.dll

How can I avoid this exception?

like image 946
Alex Zhulin Avatar asked Mar 18 '23 22:03

Alex Zhulin


2 Answers

Here is a method to check for the existence of a key:

    public static bool PropertiesHasKey(string key)
    {
        foreach (SettingsProperty sp in Properties.Settings.Default.Properties)
        {
            if (sp.Name == key)
            {
                return true;
            }
        }
        return false;
    }
like image 191
Paul Richards Avatar answered Mar 24 '23 03:03

Paul Richards


Unless that collection provides a method to check whether a given key exists then you will have to wrap the code in a try..catch block.

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

If the Default property implements the IDictionary interface you can use the ContainsKey method to test that the given key exists before trying to access it, like so:

 if(Properties.Settings.Default.ContainsKey("SelectedPath"))
 {
     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
 }else{
     folderBrowserDialog1.SelectedPath = ""; // or whatever else is appropriate in your case
 }
like image 22
Mike Dinescu Avatar answered Mar 24 '23 04:03

Mike Dinescu