Does Registry Value/Key Exsist?

  • Thread starter Thread starter Yogi_Bear_79
  • Start date Start date
Y

Yogi_Bear_79

Been trying to do an IF statement to check for a registry key. I understand
to RegistryKey class in the Microsoft.Win32 namespace. But just can't get
the syntax correct. What I want is to test for a key, if the key doesn't
exsist, then create it, if the key exists, ignore and go to next.

The following is my current code, what I want to do is incorporate an if
statement into this code. Idea being if the key already exists, go to the
next one. The below code works, but it resets the value of the keys when
they exist. By not resetting existing keys, the code should perform better.
private void AddRestrictedSites()

{

foreach(string x in strResSitesList)


{

using (RegistryKey Key = Registry.LocalMachine.CreateSubKey(sSubKey +
@"ZoneMap\Domains\" + x + @"\www\"))

{

Key.SetValue ("*", Convert.ToInt32(00000004));

}

}


}
 
Use OpenSubKey() instead of CreateSubKey() and then check for null (which
means the key does not exist).

Ken
 
Microsoft.Win32.RegistryKey subKey =
Microsoft.Win32.Registry.LocalMachine.OpenSubKey(path);

If (subKey != null)

{
//key exists
}

else

{
//key doesn't exist

}
 
Thanks so much for the example code. I see waht I was doing wrong on my
syntax, and was able to correct my code!
 
Back
Top