Alex Zhulin Alex Zhulin - 4 years ago 687
C# Question

C# Properties.Settings.Default

How to ensure that retrieving value from

For example, when I use this code:

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

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

System.Configuration.SettingsPropertyNotFoundException' occurred in

How can I avoid this exception?

Answer Source

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.

     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
     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:

     folderBrowserDialog1.SelectedPath = (string)Properties.Settings.Default["SelectedPath"];
     folderBrowserDialog1.SelectedPath = ""; // or whatever else is appropriate in your case
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download