Create a new method TryScanSubKey
. Then your code looks clean again:
TryScanSubKey(Registry.ClassesRoot);
TryScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE"));
TryScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE"));
if (Is64BitOS)
{
TryScanSubKey(Registry.ClassesRoot.OpenSubKey("Wow6432Node"));
TryScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node"));
TryScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node"));
}
The implementation of TryScanSubKey
should be obvious, but, for completeness, here it is:
void TryScanSubKey(RegistryKey key)
{
try
{
ScanSubKey(key);
}
catch (Exception ex)
{
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
}
Note that, in general, swallowing an error is bad practice, and swallowing all errors is worse still. So please consider (at least) replacing catch (Exception ex)
with something more specific, e.g. catch (TheSpecificExceptionThrownByScanSubKey ex)
.