RegistrySecurity.RemoveAccessRule(RegistryAccessRule) Метод

Определение

Осуществляет поиск правила управления доступом с тем же именем пользователя и значением AccessControlType ("разрешить" или "запретить"), что и указанного правила доступа, а также с совместимыми флагами наследования и распространения; если правило найдено, содержащиеся в указанном правиле доступа права удаляются.

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

Параметры

rule
RegistryAccessRule

Объект RegistryAccessRule, определяющий пользователя и тип AccessControlType для поиска, а также набор флагов наследования и распространения, с которыми должно быть совместимо найденное правило. Задает права, которые требуется удалить из совместимого правила, если оно будет найдено.

Возвращаемое значение

Значение true, если совместимое правило найдено; в противном случае — значение false.

Исключения

rule имеет значение null.

Примеры

В следующем примере кода показано, как RemoveAccessRule метод удаляет права из совместимого правила и как AddAccessRule метод объединяет права с совместимыми правилами.

В примере создается RegistrySecurity объект и добавляется правило, разрешающее текущие права пользователя RegistryRights.ReadKey . Затем в примере создается правило, которое предоставляет пользователю RegistryRights.SetValueте же права на наследование и распространение, что и первое правило, и использует RemoveAccessRule метод для удаления этого нового правила из RegistrySecurity объекта . SetValue является частью ReadKey, поэтому он удаляется из совместимого правила. В объекте RegistrySecurity отображаются правила, показывающие остальные компоненты ReadKey.

Затем в примере кода вызывается RemoveAccessRule метод для обратного слияния правого SetValue элемента с правилом в объекте RegistrySecurity .

Примечание

В этом примере объект безопасности не присоединяет к объекту RegistryKey . Во втором примере в этом разделе прикрепляется объект безопасности, как и в примерах в 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
'

Комментарии

Текущий RegistrySecurity ищется правило, которое имеет тот же пользователь и имеет одинаковые AccessControlType значение как rule. Если такое правило не найдено, никаких действий не выполняется, и метод возвращает false. Если правила сопоставления найдены, их флагов наследования и совместимости проверка на совместимость с флагов, указанных в rule. Если не совместимое правило найдено, никакие действия не выполняются, и метод возвращает false. Если обнаруживается правило с совместимыми флагами, права, указанные в rule удаляются из совместимого правила, а метод возвращает true. Если rule задает права, не содержится в совместимого правила, никакие действия не выполняются по отношению к эти права. Если все права удаляются из совместимого правила, правило целиком удаляется из текущей RegistrySecurity объекта.

Применяется к