FileInfo.SetAccessControl(FileSecurity) Método

Definição

Aplica-se a entradas da ACL (lista de controle de acesso) descritas por um objeto FileSecurity para o arquivo descrito pelo objeto FileInfo atual.Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileInfo object.

public:
 void SetAccessControl(System::Security::AccessControl::FileSecurity ^ fileSecurity);
public void SetAccessControl (System.Security.AccessControl.FileSecurity fileSecurity);
member this.SetAccessControl : System.Security.AccessControl.FileSecurity -> unit
Public Sub SetAccessControl (fileSecurity As FileSecurity)

Parâmetros

fileSecurity
FileSecurity

Um objeto FileSecurity que descreve uma entrada ACL (Lista de Controle de Acesso) para aplicar ao arquivo atual.A FileSecurity object that describes an access control list (ACL) entry to apply to the current file.

Exceções

O parâmetro fileSecurity é null.The fileSecurity parameter is null.

O arquivo não pôde ser encontrado ou modificado.The file could not be found or modified.

O processo atual não tem acesso para abrir o arquivo.The current process does not have access to open the file.

Exemplos

O exemplo de código a seguir usa o GetAccessControl método e o SetAccessControl método para adicionar e remover uma entrada de ACL de um arquivo.The following code example uses the GetAccessControl method and the SetAccessControl method to add and then remove an ACL entry from a file. Você deve fornecer uma conta de grupo ou de usuário válida para executar este exemplo.You must supply a valid user or group account to run this example.

#using <System.Security.dll>
using namespace System;
using namespace System::IO;
using namespace System::Security::AccessControl;
using namespace System::Security::Principal;

// Adds an ACL entry on the specified file for the specified account.
static void AddFileSecurity(String^ fileName, String^ account,
                     FileSystemRights^ rights, 
                     AccessControlType^ controlType)
{
    // Create a new FileInfo object.
    FileInfo^ fInfo = gcnew FileInfo(fileName);
    if (!fInfo->Exists)
    {
        fInfo->Create();
    }

    // Get a FileSecurity object that represents the
    // current security settings.
    FileSecurity^ fSecurity = fInfo->GetAccessControl();

    // Add the FileSystemAccessRule to the security settings.
    fSecurity->AddAccessRule(gcnew FileSystemAccessRule(account,
        *rights, *controlType));

    // Set the new access settings.
    fInfo->SetAccessControl(fSecurity);
}

// Removes an ACL entry on the specified file for the specified account.
static void RemoveFileSecurity(String^ fileName, String^ account,
                        FileSystemRights^ rights, 
                        AccessControlType^ controlType)
{
    // Create a new FileInfo object.
    FileInfo^ fInfo = gcnew FileInfo(fileName);
    if (!fInfo->Exists)
    {
        fInfo->Create();
    }

    // Get a FileSecurity object that represents the
    // current security settings.
    FileSecurity^ fSecurity = fInfo->GetAccessControl();

    // Remove the FileSystemAccessRule from the security settings.
    fSecurity->RemoveAccessRule(gcnew FileSystemAccessRule(account, 
        *rights, *controlType));

    // Set the new access settings.
    fInfo->SetAccessControl(fSecurity);
}

int main()
{
    try
    {
        String^ fileName = "c:\\test.xml";

        Console::WriteLine("Adding access control entry for " +
            fileName);

        // Add the access control entry to the file.
        // Before compiling this snippet, change MyDomain to your 
        // domain name and MyAccessAccount to the name 
        // you use to access your domain.
        AddFileSecurity(fileName, "MyDomain\\MyAccessAccount",
            FileSystemRights::ReadData, AccessControlType::Allow);

        Console::WriteLine("Removing access control entry from " +
            fileName);

        // Remove the access control entry from the file.
        // Before compiling this snippet, change MyDomain to your 
        // domain name and MyAccessAccount to the name 
        // you use to access your domain.
        RemoveFileSecurity(fileName, "MyDomain\\MyAccessAccount",
            FileSystemRights::ReadData, AccessControlType::Allow);

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

}
//This code produces output similar to the following; 
//results may vary based on the computer/file structure/etc.:
//
//Adding access control entry for c:\test.xml
//Removing access control entry from c:\test.xml
//Done.
//
using System;
using System.IO;
using System.Security.AccessControl;

namespace FileSystemExample
{
    class FileExample
    {
        public static void Main()
        {
            try
            {
                string FileName = "c:/test.xml";

                Console.WriteLine("Adding access control entry for " + FileName);

                // Add the access control entry to the file.
                // Before compiling this snippet, change MyDomain to your
                // domain name and MyAccessAccount to the name
                // you use to access your domain.
                AddFileSecurity(FileName, @"MyDomain\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow);

                Console.WriteLine("Removing access control entry from " + FileName);

                // Remove the access control entry from the file.
                // Before compiling this snippet, change MyDomain to your
                // domain name and MyAccessAccount to the name
                // you use to access your domain.
                RemoveFileSecurity(FileName, @"MyDomain\MyAccessAccount", 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)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(FileName);

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = fInfo.GetAccessControl();

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(Account,
                                                            Rights,
                                                            ControlType));

            // Set the new access settings.
            fInfo.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)
        {
            // Create a new FileInfo object.
            FileInfo fInfo = new FileInfo(FileName);

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = fInfo.GetAccessControl();

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.RemoveAccessRule(new FileSystemAccessRule(Account,
                                                            Rights,
                                                            ControlType));

            // Set the new access settings.
            fInfo.SetAccessControl(fSecurity);
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Adding access control entry for c:\test.xml
//Removing access control entry from c:\test.xml
//Done.
//
Imports System.IO
Imports System.Security.AccessControl



Module FileExample

    Sub Main()
        Try
            Dim FileName As String = "c:\test.xml"

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

            ' Add the access control entry to the file.
            ' Before compiling this snippet, change MyDomain to your 
            ' domain name and MyAccessAccount to the name 
            ' you use to access your domain.
            AddFileSecurity(FileName, "MyDomain\\MyAccessAccount", FileSystemRights.ReadData, AccessControlType.Allow)

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

            ' Remove the access control entry from the file.
            ' Before compiling this snippet, change MyDomain to your 
            ' domain name and MyAccessAccount to the name 
            ' you use to access your domain.
            RemoveFileSecurity(FileName, "MyDomain\\MyAccessAccount", 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)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(FileName)

        ' Get a FileSecurity object that represents the 
        ' current security settings.
        Dim fSecurity As FileSecurity = fInfo.GetAccessControl()

        ' Add the FileSystemAccessRule to the security settings. 
        fSecurity.AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))

        ' Set the new access settings.
        fInfo.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)
        ' Create a new FileInfo object.
        Dim fInfo As New FileInfo(FileName)

        ' Get a FileSecurity object that represents the 
        ' current security settings.
        Dim fSecurity As FileSecurity = fInfo.GetAccessControl()

        ' Add the FileSystemAccessRule to the security settings. 
        fSecurity.RemoveAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))

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

    End Sub
End Module
'This code produces output similar to the following; 
'results may vary based on the computer/file structure/etc.:
'
'Adding access control entry for c:\test.xml
'Removing access control entry from c:\test.xml
'Done.
'

Comentários

O SetAccessControl método aplica entradas de ACL (lista de controle de acesso) ao arquivo atual que representa a lista ACL não herdada.The SetAccessControl method applies access control list (ACL) entries to the current file that represents the noninherited ACL list.

Use o SetAccessControl método sempre que precisar adicionar ou remover entradas de ACL de um arquivo.Use the SetAccessControl method whenever you need to add or remove ACL entries from a file.

Cuidado

A ACL especificada para o fileSecurity parâmetro substitui a ACL existente para o arquivo.The ACL specified for the fileSecurity parameter replaces the existing ACL for the file. Para adicionar permissões para um novo usuário, use o GetAccessControl método para obter a ACL existente, modifique-a e use SetAccessControl para aplicá-la de volta ao arquivo.To add permissions for a new user, use the GetAccessControl method to obtain the existing ACL, modify it, and then use SetAccessControl to apply it back to the file.

Uma ACL descreve indivíduos e/ou grupos que têm ou não têm direitos sobre ações específicas no arquivo fornecido.An ACL describes individuals and/or groups who have, or do not have, rights to specific actions on the given file. Para saber mais, confira Como adicionar ou remover entradas da lista de controle de acesso.For more information, see How to: Add or Remove Access Control List Entries.

O SetAccessControl método persiste somente os FileSecurity objetos que foram modificados após a criação do objeto.The SetAccessControl method persists only FileSecurity objects that have been modified after object creation. Se um FileSecurity objeto não tiver sido modificado, ele não será persistido em um arquivo.If a FileSecurity object has not been modified, it will not be persisted to a file. Portanto, não é possível recuperar um FileSecurity objeto de um arquivo e reaplicar o mesmo objeto a outro arquivo.Therefore, it is not possible to retrieve a FileSecurity object from one file and reapply the same object to another file.

Para copiar informações de ACL de um arquivo para outro:To copy ACL information from one file to another:

  1. Use o GetAccessControl método para recuperar o FileSecurity objeto do arquivo de origem.Use the GetAccessControl method to retrieve the FileSecurity object from the source file.

  2. Crie um novo FileSecurity objeto para o arquivo de destino.Create a new FileSecurity object for the destination file.

  3. Use o GetSecurityDescriptorBinaryForm GetSecurityDescriptorSddlForm método ou do objeto de origem FileSecurity para recuperar as informações de ACL.Use the GetSecurityDescriptorBinaryForm or GetSecurityDescriptorSddlForm method of the source FileSecurity object to retrieve the ACL information.

  4. Use o SetSecurityDescriptorBinaryForm SetSecurityDescriptorSddlForm método ou para copiar as informações recuperadas na etapa 3 para o FileSecurity objeto de destino.Use the SetSecurityDescriptorBinaryForm or SetSecurityDescriptorSddlForm method to copy the information retrieved in step 3 to the destination FileSecurity object.

  5. Defina o objeto de destino FileSecurity para o arquivo de destino usando o SetAccessControl método.Set the destination FileSecurity object to the destination file using the SetAccessControl method.

Aplica-se a