Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello all.
I would like to know how to check if a Registry value exist in C#.
i know how to do this in VB:
VB
If Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\Software\Number Averaging Program", "SpeechEnable", Nothing) Is Nothing Then
    MsgBox("There Are No Registry Settings To Delete!", Microsoft.VisualBasic.MsgBoxStyle.OkOnly, "Number Averaging Program")
Else
    Microsoft.Win32.Registry.CurrentUser.DeleteSubKey("Software\Number Averaging Program")
    MsgBox("Registry Settings Cleared Successfully!", Microsoft.VisualBasic.MsgBoxStyle.OkOnly, "Number Averaging Program")
End If


But how would i do this in C#?
Here is what i have so far(its in C#):
C#
if (Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\Software\\On Screen Keyboard", "SpeechSave", null) is Nullable)
{
    Registry.SetValue("HKEY_CURRENT_USER\\Software\\On Screen Keyboard\\Directories", "DictationEnabled", false);
}

Thanks for all of your help in advance.
Posted
Updated 9-Dec-14 6:54am
v2

All you need is to add using to Microsoft.Win32 namespace (VB.NET project has it by deafult) and the rest is the same...

C#
using Microsoft.Win32;

// ...

if (Registry.GetValue(@"HKEY_CURRENT_USER\Software\Key-Name", "Value-Name", null) == null)
{
  // ...
}
 
Share this answer
 
v3
Comments
Richard Deeming 9-Dec-14 12:52pm    
Don't forget you need to escape the path string, or use a literal string. :)

Also, there isn't a Microsoft.Win32 assembly; it's a namespace in the mscorlib assembly.
Kornfeld Eliyahu Peter 9-Dec-14 12:58pm    
Never liked the registry...
MasterCodeon 9-Dec-14 12:52pm    
I already have a reference, and i have converted the VB if statement to the added code in the post.
Kornfeld Eliyahu Peter 9-Dec-14 12:58pm    
See the updated answer...
MasterCodeon 9-Dec-14 12:55pm    
What do you mean by "escape the path string" Richard?
do you mean use 2 \\ in stead of one?
MasterCodeon365 wrote:

is Nullable

There's your problem - that's not how you check for null / Nothing in C#.
C#
if (Registry.GetValue("HKEY_CURRENT_USER\\Software\\Number Averaging Program", "SpeechEnable", null) == null)
{
    MessageBox.Show("There Are No Registry Settings To Delete!", "Number Averaging Program");
}
else
{
    Registry.CurrentUser.DeleteSubKey("Software\\Number Averaging Program");
    MessageBox.Show("Registry Settings Cleared Successfully!", "Number Averaging Program");
}
 
Share this answer
 
Comments
MasterCodeon 9-Dec-14 13:03pm    
It works thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900