Partilhar via


FileSystemSecurity.AddAccessRule(FileSystemAccessRule) Método

Definição

Adiciona a permissão de ACL (lista de controle de acesso) especificada ao arquivo ou diretório atual.

public:
 void AddAccessRule(System::Security::AccessControl::FileSystemAccessRule ^ rule);
public void AddAccessRule (System.Security.AccessControl.FileSystemAccessRule rule);
override this.AddAccessRule : System.Security.AccessControl.FileSystemAccessRule -> unit
Public Sub AddAccessRule (rule As FileSystemAccessRule)

Parâmetros

rule
FileSystemAccessRule

Um objeto FileSystemAccessRule que representa uma permissão acl (lista de controle de acesso) para adicionar a um arquivo ou diretório.

Exceções

O parâmetro rule é null.

Exemplos

O exemplo de código a seguir usa a classe FileSecurity para adicionar e, em seguida, remover uma entrada de ACL (lista de controle de acesso) de um arquivo. Você deve fornecer uma conta de usuário ou grupo válida para executar este exemplo.

using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                string fileName = "test.xml";

                Console.WriteLine($"Adding access control entry for {fileName}");

                // Add the access control entry to the file.
                AddFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.ReadData, AccessControlType.Allow);

                Console.WriteLine($"Removing access control entry from {fileName}");

                // Remove the access control entry from the file.
                RemoveFileSecurity(fileName, @"DomainName\AccountName",
                    FileSystemRights.ReadData, AccessControlType.Allow);

                Console.WriteLine("Done.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        // Adds an ACL entry on the specified file for the specified account.
        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {
            FileInfo fileInfo = new(fileName);
            FileSecurity fSecurity = fileInfo.GetAccessControl();

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            fileInfo.SetAccessControl(fSecurity);
        }

        // Removes an ACL entry on the specified file for the specified account.
        public static void RemoveFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {
            FileInfo fileInfo = new(fileName);
            FileSecurity fSecurity = fileInfo.GetAccessControl();

            // Remove the FileSystemAccessRule from the security settings.
            fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            fileInfo.SetAccessControl(fSecurity);
        }
    }
}
Imports System.IO
Imports System.Security.AccessControl

Module FileExample

    Sub Main()
        Try
            Dim fileName As String = "test.xml"

            Console.WriteLine("Adding access control entry for " & fileName)

            ' Add the access control entry to the file.
            AddFileSecurity(fileName, "DomainName\AccountName",
                FileSystemRights.ReadData, AccessControlType.Allow)

            Console.WriteLine("Removing access control entry from " & fileName)

            ' Remove the access control entry from the file.
            RemoveFileSecurity(fileName, "DomainName\AccountName",
                FileSystemRights.ReadData, AccessControlType.Allow)

            Console.WriteLine("Done.")
        Catch e As Exception
            Console.WriteLine(e)
        End Try

    End Sub

    ' Adds an ACL entry on the specified file for the specified account.
    Sub AddFileSecurity(ByVal fileName As String, ByVal account As String,
        ByVal rights As FileSystemRights, ByVal controlType As AccessControlType)

        Dim fileInfo As New FileInfo(fileName)
        Dim fSecurity As FileSecurity = fileInfo.GetAccessControl()

        ' Add the FileSystemAccessRule to the security settings. 
        Dim accessRule As New FileSystemAccessRule(account, rights, controlType)

        fSecurity.AddAccessRule(accessRule)

        ' Set the new access settings.
        fileInfo.SetAccessControl(fSecurity)

    End Sub

    ' Removes an ACL entry on the specified file for the specified account.
    Sub RemoveFileSecurity(ByVal fileName As String, ByVal account As String,
        ByVal rights As FileSystemRights, ByVal controlType As AccessControlType)

        Dim fileInfo As New FileInfo(fileName)
        Dim fSecurity As FileSecurity = fileInfo.GetAccessControl()

        ' Remove the FileSystemAccessRule from the security settings. 
        fSecurity.RemoveAccessRule(New FileSystemAccessRule(account,
            rights, controlType))

        ' Set the new access settings.
        fileInfo.SetAccessControl(fSecurity)

    End Sub
End Module

Comentários

O método AddAccessRule adiciona uma nova regra à lista de regras contidas em um objeto FileSystemSecurity.

Se já existir uma ACL (lista de controle de acesso) para a regra especificada, o método AddAccessRule ainda adicionará a regra, com uma exceção: um objeto FileSystemAccessRule criado usando o valor de enumeração Deny substituirá um objeto criado usando o valor de enumeração Allow.

Use os seguintes métodos dependentes de implementação do .NET para adicionar ou recuperar informações de ACL de um arquivo:

Implementação do .NET Adicionar regras Recuperar regras
.REDE FileSystemAclExtensions.SetAccessControl(FileInfo, FileSecurity) FileSystemAclExtensions.GetAccessControl(FileInfo)
.NET Framework FileInfo.SetAccessControl(FileSecurity) FileInfo.GetAccessControl()

Quando você adiciona uma regra de acesso sem definir o sinalizador de Synchronize, o sinalizador Synchronize será adicionado automaticamente à sua regra. Se você remover a regra mais tarde sem especificar o sinalizador Synchronize, o sinalizador será removido automaticamente.

Aplica-se a