Share via


RegistrySecurity.RemoveAccessRule(RegistryAccessRule) Método

Definição

Pesquisa por uma regra de controle de acesso com o mesmo usuário e AccessControlType (permitir ou negar) como a regra de acesso especificada e com sinalizadores de herança e de propagação compatíveis; se uma regra com essas características for encontrada, os direitos contidos na regra de acesso especificada serão removidos dela.

public:
 bool RemoveAccessRule(System::Security::AccessControl::RegistryAccessRule ^ rule);
public bool RemoveAccessRule (System.Security.AccessControl.RegistryAccessRule rule);
override this.RemoveAccessRule : System.Security.AccessControl.RegistryAccessRule -> bool
Public Function RemoveAccessRule (rule As RegistryAccessRule) As Boolean

Parâmetros

rule
RegistryAccessRule

Um RegistryAccessRule que especifica o usuário e AccessControlType pelo qual pesquisar, bem como um conjunto de sinalizadores de herança e de propagação com os quais uma regra correspondente, se encontrada, deve ser compatível. Especifica os direitos a serem removidos da regra compatível, se encontrado.

Retornos

true se uma regra compatível for encontrada; caso contrário, false.

Exceções

rule é null.

Exemplos

O exemplo de código a seguir mostra como o RemoveAccessRule método remove direitos de uma regra compatível e como o AddAccessRule método mescla direitos com regras compatíveis.

O exemplo cria um RegistrySecurity objeto e adiciona uma regra que permite os direitos de usuário RegistryRights.ReadKey atuais. Em seguida, o exemplo cria uma regra que concede ao usuário RegistryRights.SetValue, com os mesmos direitos de herança e propagação que a primeira regra, e usa o RemoveAccessRule método para remover essa nova regra do RegistrySecurity objeto . SetValue é um constituinte de ReadKey, portanto, ele é removido da regra compatível. As regras no RegistrySecurity objeto são exibidas, mostrando os componentes restantes de ReadKey.

Em seguida, o código de exemplo chama o RemoveAccessRule método para mesclar o SetValue direito de volta à regra no RegistrySecurity objeto .

Observação

Este exemplo não anexa o objeto de segurança a um RegistryKey objeto . O segundo exemplo nesta seção anexa um objeto de segurança, assim como os exemplos em RegistryKey.GetAccessControlRegistryKey.SetAccessControl.


using System;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Security;
using Microsoft.Win32;

public class Example
{

    public static void Main()
    {

        string user = Environment.UserDomainName + "\\"
            + Environment.UserName;

        // Create a security object that grants no access.
        RegistrySecurity mSec = new RegistrySecurity();

        // Add a rule that grants the current user ReadKey
        // rights. ReadKey is a combination of four other 
        // rights. The rule is inherited by all 
        // contained subkeys.
        RegistryAccessRule rule = new RegistryAccessRule(user, 
            RegistryRights.ReadKey, 
            InheritanceFlags.ContainerInherit, 
            PropagationFlags.None, 
            AccessControlType.Allow);
        mSec.AddAccessRule(rule);

        // Create a rule that allows the current user only the 
        // right to query the key/value pairs of a key, using  
        // the same inheritance and propagation flags as the
        // first rule. QueryValues is a constituent of 
        // ReadKey, so when this rule is removed, using the 
        // RemoveAccessRule method, ReadKey is broken into
        // its constituent parts.
        rule = new RegistryAccessRule(user, 
            RegistryRights.QueryValues, 
            InheritanceFlags.ContainerInherit, 
            PropagationFlags.None, 
            AccessControlType.Allow);
        mSec.RemoveAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);

        // Add the second rule back. It merges with the 
        // existing rule, so that the rule is now displayed
        // as ReadKey.
        mSec.AddAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);
    }

    private static void ShowSecurity(RegistrySecurity security)
    {
        Console.WriteLine("\r\nCurrent access rules:\r\n");

        foreach( RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)) )
        {
            Console.WriteLine("        User: {0}", ar.IdentityReference);
            Console.WriteLine("        Type: {0}", ar.AccessControlType);
            Console.WriteLine("      Rights: {0}", ar.RegistryRights);
            Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
            Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
            Console.WriteLine("   Inherited? {0}", ar.IsInherited);
            Console.WriteLine();
        }
    }
}

/* This code example produces output similar to following:

Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: EnumerateSubKeys, Notify, ReadPermissions
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? False


Current access rules:

        User: TestDomain\TestUser
        Type: Allow
      Rights: ReadKey
 Inheritance: ContainerInherit
 Propagation: None
   Inherited? False
 */
Option Explicit
Imports System.Security.AccessControl
Imports System.Security.Principal
Imports System.Security
Imports Microsoft.Win32

Public Class Example

    Public Shared Sub Main()

        Dim user As String = Environment.UserDomainName _ 
            & "\" & Environment.UserName

        ' Create a security object that grants no access.
        Dim mSec As New RegistrySecurity()

        ' Add a rule that grants the current user ReadKey
        ' rights. ReadKey is a combination of four other 
        ' rights. The rule is inherited by all 
        ' contained subkeys.
        Dim rule As New RegistryAccessRule(user, _
            RegistryRights.ReadKey, _
            InheritanceFlags.ContainerInherit, _
            PropagationFlags.None, _
            AccessControlType.Allow)
        mSec.AddAccessRule(rule)

        ' Create a rule that allows the current user only the 
        ' right to query the key/value pairs of a key, using  
        ' the same inheritance and propagation flags as the
        ' first rule. QueryValues is a constituent of 
        ' ReadKey, so when this rule is removed, using the 
        ' RemoveAccessRule method, ReadKey is broken into
        ' its constituent parts.
        rule = New RegistryAccessRule(user, _
            RegistryRights.QueryValues, _
            InheritanceFlags.ContainerInherit, _
            PropagationFlags.None, _
            AccessControlType.Allow)
        mSec.RemoveAccessRule(rule)

        ' Display the rules in the security object.
        ShowSecurity(mSec)

        ' Add the second rule back. It merges with the 
        ' existing rule, so that the rule is now displayed
        ' as ReadKey.
        mSec.AddAccessRule(rule)

        ' Display the rules in the security object.
        ShowSecurity(mSec)

    End Sub 

    Private Shared Sub ShowSecurity(ByVal security As RegistrySecurity)
        Console.WriteLine(vbCrLf & "Current access rules:" & vbCrLf)

        For Each ar As RegistryAccessRule In _
            security.GetAccessRules(True, True, GetType(NTAccount))

            Console.WriteLine("        User: {0}", ar.IdentityReference)
            Console.WriteLine("        Type: {0}", ar.AccessControlType)
            Console.WriteLine("      Rights: {0}", ar.RegistryRights)
            Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags)
            Console.WriteLine(" Propagation: {0}", ar.PropagationFlags)
            Console.WriteLine("   Inherited? {0}", ar.IsInherited)
            Console.WriteLine()
        Next

    End Sub
End Class 

'This code example produces output similar to following:
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: EnumerateSubKeys, Notify, ReadPermissions
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? False
'
'
'Current access rules:
'
'        User: TestDomain\TestUser
'        Type: Allow
'      Rights: ReadKey
' Inheritance: ContainerInherit
' Propagation: None
'   Inherited? False
'

Comentários

O atual RegistrySecurity é pesquisado por uma regra que tem o mesmo usuário e o mesmo AccessControlType valor que rule. Se nenhuma regra desse tipo for encontrada, nenhuma ação será tomada e o método retornará false. Se forem encontradas regras de correspondência, seus sinalizadores de herança e compatibilidade serão verificados quanto à compatibilidade com os sinalizadores especificados em rule. Se nenhuma regra compatível for encontrada, nenhuma ação será tomada e o método retornará false. Se uma regra com sinalizadores compatíveis for encontrada, os direitos especificados em rule serão removidos da regra compatível e o método retornará true. Se rule especificar direitos não contidos na regra compatível, nenhuma ação será tomada em relação a esses direitos. Se todos os direitos forem removidos da regra compatível, toda a regra será removida do objeto atual RegistrySecurity .

Aplica-se a