Question

I'm trying to make a generic function to set the registry user permissions.

The problem is, if I deny the fullcontrol acces of a key using the code then If I will allow it again it throws an exception when is trying to read the key at this line:

    Dim RK As RegistryKey = RootKey.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions Or RegistryRights.ReadKey)

I call the procedure like this:

 RegEdit.Set_UserAccess_Key("hkcu\appevents", RegistryRights.FullControl, AccessControlType.Deny)

That is working, and after that I call this:

 RegEdit.Set_UserAccess_Key("hkcu\appevents", RegistryRights.FullControl, AccessControlType.Allow)

The exception when I try to allow a previously denied permission:

Requested registry access denied

Acceso denegado al Registro solicitado.

This is the code:

''' <summary>
''' Modify the User permissions of a registry key.
''' </summary>
Public Shared Sub Set_UserAccess_Key(ByVal RegKey As String, _
                                     ByVal RegUserAccess As RegistryRights, _
                                     ByVal AccessType As AccessControlType, _
                                     Optional ByVal UserName As String = Nothing)

    If UserName = Nothing Then UserName = Environment.UserDomainName & "\" & Environment.UserName

    Dim RootKey As RegistryKey = Get_Root_Key(RegKey) ' Registrykey.Currentuser
    Dim KeyPath As String = Get_Key_Path(RegKey) ' AppEvents

    Dim RS As New RegistrySecurity()
    Dim RK As RegistryKey = RootKey.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions Or RegistryRights.ReadKey)

    RS.AddAccessRule(New RegistryAccessRule(UserName, RegUserAccess, InheritanceFlags.None, PropagationFlags.None, AccessType))
    RK.SetAccessControl(RS)
    RK = RootKey.OpenSubKey(KeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegUserAccess)
    RK.SetAccessControl(RS)

End Sub
Was it helpful?

Solution

I wrote a small program some time ago to grant full access to a given Registry Key. It did always work fine. Its code is equivalent to yours except for:

RS.AddAccessRule(New RegistryAccessRule(UserName, RegistryRights.CreateSubKey Or RegistryRights.Delete Or RegistryRights.ExecuteKey Or RegistryRights.FullControl Or RegistryRights.ReadKey Or RegistryRights.SetValue Or RegistryRights.WriteKey, AccessControlType.Allow))

Not sure if there is any change with respect to your code (you are using variables whose content I cannot know). In any case, note that this app never accessed the given key right after having changed the security level. The process was: first execution to set full access to the key; a different execution to access the modified key.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top