Search code examples
.netvb.netpermissionsregistryrepeat

Creating 7 registry values under a registry key without repetition


I am developing an windows application using vb.net. Now I want to add 7 values in registry HKEY_CURRENT_USER\SOFTWARE\MYAPP.

Each value (out of 7) should be added only when it does not exist in the subkey.

In the end I want to see only 7 under MYAPP SUBKEY. How do I do that? I need your help.


Solution

  • You can use the GetValue of a RegistryKey object and test the result, if Nothing then the value does not exist.

    Here is a complete example that should get you working. Note that you might need admin rights to create keys and values depending on the machine permissions:

        Dim myAppKey = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.CurrentUser, Microsoft.Win32.RegistryView.Default)
        If myAppKey Is Nothing Then Throw New Exception("Failed to open registry")
    
        Dim subKeyName = "SOFTWARE\MYAPP"
    
        'attempt to open the subkey with write acces because we need this if we are creating values
        Dim subKey = myAppKey.OpenSubKey(subKeyName, True)
        If subKey Is Nothing Then
            'create the sub key because it doesn't exist
            myAppKey.CreateSubKey(subKeyName)
            're open the new key
            subKey = myAppKey.OpenSubKey(subKeyName, True)
        End If
    
        'create values in a loop for testing
        For i = 0 To 6
            If subKey.GetValue("Value" & i) Is Nothing Then
                'value does not exist so create it
                subKey.SetValue("Value" & i, i)
            End If
        Next