FileSystemAccessRule Класс

Определение

Представляет абстракцию элемента управления доступом, определяющую правило доступа для файла или каталога. Этот класс не наследуется.

public ref class FileSystemAccessRule sealed : System::Security::AccessControl::AccessRule
public sealed class FileSystemAccessRule : System.Security.AccessControl.AccessRule
[System.Security.SecurityCritical]
public sealed class FileSystemAccessRule : System.Security.AccessControl.AccessRule
type FileSystemAccessRule = class
    inherit AccessRule
[<System.Security.SecurityCritical>]
type FileSystemAccessRule = class
    inherit AccessRule
Public NotInheritable Class FileSystemAccessRule
Inherits AccessRule
Наследование
FileSystemAccessRule
Атрибуты

Примеры

В следующем примере кода класс используется для FileSecurity добавления и удаления записи управления доступом (ACE) из файла. Для выполнения этого примера необходимо указать допустимую учетную запись пользователя или группы.

using namespace System;
using namespace System::IO;
using namespace System::Security::AccessControl;

// Adds an ACL entry on the specified file for the specified account.

void AddFileSecurity(String^ fileName, String^ account, 
                        FileSystemRights rights, AccessControlType controlType)
{
    // Get a FileSecurity object that represents the 
    // current security settings.
    FileSecurity^ fSecurity = File::GetAccessControl(fileName);

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

    // Set the new access settings.
    File::SetAccessControl(fileName, fSecurity);
}

// Removes an ACL entry on the specified file for the specified account.

void RemoveFileSecurity(String^ fileName, String^ account, 
                        FileSystemRights rights, AccessControlType controlType)
{

    // Get a FileSecurity object that represents the 
    // current security settings.
    FileSecurity^ fSecurity = File::GetAccessControl(fileName);

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

    // Set the new access settings.
    File::SetAccessControl(fileName, fSecurity);
}

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

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

        // Add the access control entry to the file.
        AddFileSecurity(fileName, "MYDOMAIN\\MyAccount", 
            FileSystemRights::ReadData, AccessControlType::Allow);

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

        // Remove the access control entry from the file.
        RemoveFileSecurity(fileName, "MYDOMAIN\\MyAccount", 
            FileSystemRights::ReadData, AccessControlType::Allow);

        Console::WriteLine("Done.");
    }
    catch (Exception^ ex)
    {
        Console::WriteLine(ex->Message);
    }
}
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)
        {

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

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

            // Set the new access settings.
            File.SetAccessControl(fileName, 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)
        {

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

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

            // Set the new access settings.
            File.SetAccessControl(fileName, 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)
  
        ' Get a FileSecurity object that represents the 
        ' current security settings.
        Dim fSecurity As FileSecurity = File.GetAccessControl(fileName)

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

        fSecurity.AddAccessRule(accessRule)

        ' Set the new access settings.
        File.SetAccessControl(fileName, 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)

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

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

        ' Set the new access settings.
        File.SetAccessControl(fileName, fSecurity)

    End Sub
End Module

Комментарии

Класс FileSystemAccessRule представляет абстракцию базовой записи управления доступом (ACE), которая указывает учетную запись пользователя, тип доступа для предоставления (чтение, запись и т. д.), а также указывает, следует ли разрешать или запрещать это право. Этот класс также может указать, как правила доступа распространяются на дочерние объекты.

Используйте класс , FileSystemAccessRule чтобы создать новое правило доступа. Правило можно сохранить с помощью FileSecurity класса или DirectorySecurity .

Конструкторы

FileSystemAccessRule(IdentityReference, FileSystemRights, AccessControlType)

Инициализирует новый экземпляр класса FileSystemAccessRule, используя ссылку на учетную запись пользователя, значение, определяющее тип операции, связанной с правилом доступа, а также признак разрешения или запрета этой операции.

FileSystemAccessRule(IdentityReference, FileSystemRights, InheritanceFlags, PropagationFlags, AccessControlType)

Инициализирует новый экземпляр класса FileSystemAccessRule, используя ссылку на учетную запись пользователя, значение, определяющее тип связанных с правилом доступа операций, значение, определяющее порядок наследования прав, значение, определяющее порядок распространения прав, а также признак разрешения или запрета этой операции.

FileSystemAccessRule(String, FileSystemRights, AccessControlType)

Инициализирует новый экземпляр класса FileSystemAccessRule, используя имя учетной записи пользователя, значение, определяющее тип операции, связанной с правилом доступа, а также признак разрешения или запрета этой операции.

FileSystemAccessRule(String, FileSystemRights, InheritanceFlags, PropagationFlags, AccessControlType)

Инициализирует новый экземпляр класса FileSystemAccessRule, используя имя учетной записи пользователя, значение, определяющее тип связанных с правилом доступа операций, значение, определяющее порядок наследования прав, значение, определяющее порядок распространения прав, а также признак разрешения или запрета этой операции.

Свойства

AccessControlType

Получает значение AccessControlType, связанное с данным объектом AccessRule.

(Унаследовано от AccessRule)
AccessMask

Возвращает маску доступа для этого правила.

(Унаследовано от AuthorizationRule)
FileSystemRights

Получает флаги FileSystemRights, связанные с текущим объектом FileSystemAccessRule.

IdentityReference

Возвращает IdentityReference, к которому применяется это правило.

(Унаследовано от AuthorizationRule)
InheritanceFlags

Возвращает значение флагов, определяющих способ наследования этого правила дочерними объектами.

(Унаследовано от AuthorizationRule)
IsInherited

Получает значение, указывающее, задано ли это правило явно или унаследовано от родительского объекта контейнера.

(Унаследовано от AuthorizationRule)
PropagationFlags

Получает значение флагов распространения, которые определяют, как наследование этого правила распространяется на дочерние объекты. Это свойство является значимым, только когда значением перечисления InheritanceFlags не является None.

(Унаследовано от AuthorizationRule)

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

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