FileInfo.SetAccessControl(FileSecurity) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Aplica entradas da lista de controlo de acesso (ACL) descritas por um FileSecurity objeto ao ficheiro descrito pelo objeto atual 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
Um objeto que descreve uma entrada de FileSecurity lista de controlo de acesso (ACL) para aplicar ao ficheiro atual.
Exceções
O fileSecurity parâmetro é null.
O ficheiro não pôde ser encontrado nem modificado.
O processo atual não tem acesso para abrir o ficheiro.
Exemplos
O seguinte exemplo de código utiliza o GetAccessControl método e o SetAccessControl método para adicionar e depois remover uma entrada ACL de um ficheiro. Deve fornecer uma conta de utilizador 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 = "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.
'
Observações
O SetAccessControl método aplica entradas da lista de controlo de acesso (ACL) ao ficheiro atual que representa a lista ACL não herdada.
Use o SetAccessControl método sempre que precisar de adicionar ou remover entradas ACL de um ficheiro.
Atenção
A ACL especificada para o fileSecurity parâmetro substitui a ACL existente do ficheiro. Para adicionar permissões a um novo utilizador, use o GetAccessControl método para obter a ACL existente, modifique-a e depois use SetAccessControl para a aplicar novamente ao ficheiro.
Uma ACL descreve indivíduos e grupos que têm, ou não têm, direitos sobre ações específicas no determinado ficheiro. Para obter mais informações, consulte Como adicionar ou remover entradas da lista de controle de acesso.
O SetAccessControl método persiste apenas FileSecurity objetos que foram modificados após a criação do objeto. Se um FileSecurity objeto não tiver sido modificado, não será persistido para um ficheiro. Portanto, não é possível recuperar um FileSecurity objeto de um ficheiro e reaplicar o mesmo objeto a outro ficheiro.
Para copiar informação ACL de um ficheiro para outro:
Use o GetAccessControl método para recuperar o FileSecurity objeto do ficheiro de origem.
Crie um novo FileSecurity objeto para o ficheiro de destino.
Use o GetSecurityDescriptorBinaryForm método ou GetSecurityDescriptorSddlForm do objeto fonte FileSecurity para recuperar a informação ACL.
Use o SetSecurityDescriptorBinaryForm método ou SetSecurityDescriptorSddlForm para copiar a informação recuperada no passo 3 para o objeto de destino FileSecurity .
Defina o objeto de destino FileSecurity para o ficheiro de destino usando o SetAccessControl método.