FileInfo.SetAccessControl(FileSecurity) Método

Definición

Aplica entradas de lista de control de acceso (ACL) descritas por un FileSecurity objeto al archivo descrito por el objeto actual FileInfo .

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

Objeto FileSecurity que describe una entrada de lista de control de acceso (ACL) que se va a aplicar al archivo actual.

Excepciones

El fileSecurity parámetro es null.

No se encontró ni modificó el archivo.

El proceso actual no tiene acceso para abrir el archivo.

Ejemplos

En el ejemplo de código siguiente se usa el GetAccessControl método y el SetAccessControl método para agregar y, a continuación, quitar una entrada de ACL de un archivo. Debe proporcionar una cuenta de usuario o grupo válida para ejecutar este ejemplo.

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(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(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.
'

Comentarios

El SetAccessControl método aplica entradas de lista de control de acceso (ACL) al archivo actual que representa la lista de ACL noheritadas.

Use el SetAccessControl método siempre que necesite agregar o quitar entradas de ACL de un archivo.

Caution

La ACL especificada para el fileSecurity parámetro reemplaza la ACL existente para el archivo. Para agregar permisos para un nuevo usuario, use el GetAccessControl método para obtener la ACL existente, modificarla y, a continuación, usarla SetAccessControl para volver a aplicarla al archivo.

Una ACL describe individuos y grupos que tienen derechos, o no, a acciones específicas en el archivo especificado. Para obtener más información, vea Cómo: Agregar o quitar entradas de lista de control de acceso.

El SetAccessControl método conserva solo FileSecurity los objetos que se han modificado después de la creación del objeto. Si no se ha modificado un FileSecurity objeto, no se conservará en un archivo. Por lo tanto, no es posible recuperar un FileSecurity objeto de un archivo y volver a aplicar el mismo objeto a otro archivo.

Para copiar información de ACL de un archivo a otro:

  1. Use el GetAccessControl método para recuperar el FileSecurity objeto del archivo de origen.

  2. Cree un nuevo FileSecurity objeto para el archivo de destino.

  3. Utilice el GetSecurityDescriptorBinaryForm método o GetSecurityDescriptorSddlForm del objeto de origen FileSecurity para recuperar la información de la ACL.

  4. Use el SetSecurityDescriptorBinaryForm método o SetSecurityDescriptorSddlForm para copiar la información recuperada en el paso 3 al objeto de destino FileSecurity .

  5. Establezca el objeto de destino FileSecurity en el archivo de destino mediante el SetAccessControl método .

Se aplica a