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?
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;
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With