RegistryKey.OpenSubKey does not ALWAYS return an existing value

Paul Goldstein 116 Reputation points
2021-08-06T18:07:24.077+00:00

I have a VB WinForms program that interacts with the Registry.
Recently, I have come upon an error, that should not be occurring.
Here is the setup to reading the next SubKey:

        Dim rkLocalMachine, rkCurrentUser, rkSoftware, rkForceware, As RegistryKey
        Dim rsCurrent As New RegistrySecurity()
        Dim strUser As String = Environment.UserDomainName & "\" & Environment.UserName
        Dim ruleRegistryAccess As New RegistryAccessRule(strUser, RegistryRights.WriteKey, AccessControlType.Allow)

        rsCurrent.AddAccessRule(New RegistryAccessRule(strUser, RegistryRights.FullControl, AccessControlType.Allow))
        rkLocalMachine = Registry.LocalMachine
        rkCurrentUser = Registry.CurrentUser
        rkSoftware = rkCurrentUser.OpenSubKey("Software", True)

When I try the next command:

        rkForceware = rkSoftware.OpenSubKey("Forceware Systems, Inc.", True)

rkForceware is Nothing.
The problem is that, the next section of code is in place for “Creating” the Key if this is the first time that the program is running on the Target machine:

        If (rkForceware Is Nothing) Then
            rkForceware = rkSoftware.CreateSubKey("Forceware Systems, Inc.", RegistryKeyPermissionCheck.Default, rsCurrent)
        End If

This then blows up the program since the Key already exists. However, when I am in debug mode, and I tell the debugger to execute the rkSoftware.OpenSubKey command AGAIN, it reads the entry correctly, and I can tell the program to continue executing.

Why is this happening?

The Registry value has been in the Registry for a very long time…depending on the installation of the program on a Target machine, it could be there for years.

Any ideas would be greatly appreciated.

Thank you for your time in advance.
Sincerely,
Paul Goldstein

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,738 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.