Alex Zhulin Alex Zhulin - 2 years ago 573
C# Question

C# Properties.Settings.Default

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?

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.

 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
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download