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