在注册表项下创建 7 个注册表值而不重复

Creating 7 registry values under a registry key without repetition

我正在使用 vb.net 开发 windows 应用程序。现在我想在注册表 HKEY_CURRENT_USER\SOFTWARE\MYAPP 中添加 7 个值。

每个值(共 7 个)只有在子项中不存在时才应添加。

最后我只想看到MYAPP SUBKEY下的7个。我怎么做?我需要你的帮助。

您可以使用RegistryKey对象的GetValue并测试结果,如果Nothing则该值不存在。

这是一个完整的示例,应该可以帮助您工作。请注意,您可能需要管理员权限才能根据计算机权限创建键和值:

    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