Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to understand how Registry works under c#.

All examples that I have found are pretty much same, but I always get null as a result, and I am sure that registry path DOES exists.

For example, I want to check if this registry key (path) exists:

SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate under HKLM.

I am not looking for strings or values, just if KEY exists or not.

Thank you all for your suggestions.

What I have tried:

var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate");
if (key == null)
{
// Not exists
}
else
{
// Exists
}
Posted
Updated 8-Oct-19 7:55am
Comments
RickZeeland 6-Oct-19 16:18pm    
Are you compiling for 32 or 64 bits ? this can make a difference for which registry is being used.
AlexaRS 6-Oct-19 16:44pm    
Hi, it is 32bit
AlexaRS 6-Oct-19 16:58pm    
Rick,

it works as x64, but I need it in x86

Quote:
it works as x64, but I need it in x86

You need to specify the RegistryView that you want to access:
C#
using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate"))
{
    if (key == null)
    {
        // Doesn't exist...
    }
    else
    {
        // Exists...
    }
}
RegistryView Enum (Microsoft.Win32) | Microsoft Docs[^]
 
Share this answer
 
Comments
[no name] 8-Oct-19 14:15pm    
+5
Accessing anything in the registry which is not in the CURRENT_USER hive requires administrative access.
Try to launch your program as an administrator, and see if that solves your issue.
 
Share this answer
 
Comments
AlexaRS 6-Oct-19 16:27pm    
Hi phil.o

it's same behavior, I am local admin, I have turned off UAC, run as admin but it is null.

Meantime, I have noticed that I can reach
SOFTWARE\Microsoft\Windows\CurrentVersion but not SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate, very strange

On the other hand, I have PS script that works fine and can reach all keys in the node.
phil.o 6-Oct-19 16:32pm    
If you check the access rights on said key, you may find out that it has special access rights which prevent you from reading it.
I have checked on Windows 7, mine does not seem to be protected. This could have been changed on more recent versions.
AlexaRS 6-Oct-19 16:35pm    
Not a permissions issue. Checked, local admins have full control, and I am able to edit subkeys and values via regedit.
phil.o 6-Oct-19 16:50pm    
As Rick suggested, try to compile your program in 64-bits, and see if that changes the result.
AlexaRS 6-Oct-19 16:56pm    
yes, it does get subkeys. but I need it in x86.

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