Прочитать на английском

Поделиться через


RegistryRights Перечисление

Определение

Определяет права доступа, которые можно применять к объектам реестра.

Это перечисление поддерживает побитовую комбинацию значений его членов.

[System.Flags]
public enum RegistryRights
Наследование
RegistryRights
Атрибуты

Поля

ChangePermissions 262144

Право изменять правила доступа и аудита, связанные с разделом реестра.

32

Зарезервировано для системного использования.

CreateSubKey 4

Право создавать подразделы в разделе реестра.

Delete 65536

Право удалить раздел реестра.

EnumerateSubKeys 8

Право создавать список подразделов в разделе реестра.

ExecuteKey 131097

Эквивалентно ReadKey.

FullControl 983103

Право на полный контроль над разделом реестра, а также на изменение правил доступа и аудита.

Notify 16

Право запрашивать уведомление об изменениях раздела реестра.

QueryValues 1

Право запрашивать пары "имя-значение" в разделе реестра.

ReadKey 131097

Право запрашивать пары "имя-значение" в разделе реестра, запрашивать уведомление об изменениях, получать список подразделов, а также право на чтение правил доступа и аудита раздела.

ReadPermissions 131072

Право открывать и копировать правила доступа и аудита, связанные с разделом реестра.

SetValue 2

Право создавать, удалять и задавать пары "имя-значение" в разделе реестра.

TakeOwnership 524288

Право изменять владельца раздела реестра.

WriteKey 131078

Право создавать, удалять и задавать пары "имя-значение" в разделе реестра, создавать и удалять подразделы, запрашивать уведомление об изменениях, получать список подразделов, а также право на чтение правил доступа и аудита раздела.

Примеры

В следующем примере кода показано использование перечисления RegistryRights . Код создает тестовый ключ, разрешая текущим пользователям права доступа ReadKey и Delete, но запрещая права ChangePermissions и WriteKey. Последующие попытки манипулировать ключом успешно или завершаются сбоем в зависимости от этих разрешений.

Перед удалением ключа код приостанавливается. Вы можете перейти в редактор реестра (Regedit.exe или Regedt32.exe) и убедиться, что те же права доступа применяются при доступе к разделу с помощью редактора реестра.

Этот пример лучше всего подходит для запуска редактора реестра и примера кода в качестве локального пользователя без прав администратора. Например, если вы определили локального пользователя TestUser, команда runas /user:TestUser cmd открывает командное окно, из которого можно запустить редактор реестра, а затем пример кода.

using System;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // Delete the example key if it exists.
        try
        {
            Registry.CurrentUser.DeleteSubKey("RegistryRightsExample");
            Console.WriteLine("Example key has been deleted.");
        }
        catch (ArgumentException)
        {
            // ArgumentException is thrown if the key does not exist. In
            // this case, there is no reason to display a message.
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unable to delete the example key: {0}", ex);
            return;
        }

        string user = Environment.UserDomainName + "\\" + Environment.UserName;

        RegistrySecurity rs = new RegistrySecurity();

        // Allow the current user to read and delete the key.
        //
        rs.AddAccessRule(new RegistryAccessRule(user,
            RegistryRights.ReadKey | RegistryRights.Delete,
            InheritanceFlags.None,
            PropagationFlags.None,
            AccessControlType.Allow));

        // Prevent the current user from writing or changing the
        // permission set of the key. Note that if Delete permission
        // were not allowed in the previous access rule, denying
        // WriteKey permission would prevent the user from deleting the
        // key.
        rs.AddAccessRule(new RegistryAccessRule(user,
            RegistryRights.WriteKey | RegistryRights.ChangePermissions,
            InheritanceFlags.None,
            PropagationFlags.None,
            AccessControlType.Deny));

        // Create the example key with registry security.
        RegistryKey rk = null;
        try
        {
            rk = Registry.CurrentUser.CreateSubKey("RegistryRightsExample",
                RegistryKeyPermissionCheck.Default, rs);
            Console.WriteLine("\r\nExample key created.");
            rk.SetValue("ValueName", "StringValue");
        }
        catch (Exception ex)
        {
            Console.WriteLine("\r\nUnable to create the example key: {0}", ex);
        }
        if (rk != null) rk.Close();

        rk = Registry.CurrentUser;

        RegistryKey rk2;

        // Open the key with read access.
        rk2 = rk.OpenSubKey("RegistryRightsExample", false);
        Console.WriteLine("\r\nRetrieved value: {0}", rk2.GetValue("ValueName"));
        rk2.Close();

        // Attempt to open the key with write access.
        try
        {
            rk2 = rk.OpenSubKey("RegistryRightsExample", true);
        }
        catch (SecurityException ex)
        {
            Console.WriteLine("\nUnable to write to the example key." +
                " Caught SecurityException: {0}", ex.Message);
        }
        if (rk2 != null) rk2.Close();

        // Attempt to change permissions for the key.
        try
        {
            rs = new RegistrySecurity();
            rs.AddAccessRule(new RegistryAccessRule(user,
                RegistryRights.WriteKey,
                InheritanceFlags.None,
                PropagationFlags.None,
                AccessControlType.Allow));
            rk2 = rk.OpenSubKey("RegistryRightsExample", false);
            rk2.SetAccessControl(rs);
            Console.WriteLine("\r\nExample key permissions were changed.");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("\nUnable to change permissions for the example key." +
                " Caught UnauthorizedAccessException: {0}", ex.Message);
        }
        if (rk2 != null) rk2.Close();

        Console.WriteLine("\r\nPress Enter to delete the example key.");
        Console.ReadLine();

        try
        {
            rk.DeleteSubKey("RegistryRightsExample");
            Console.WriteLine("Example key was deleted.");
        }
        catch(Exception ex)
        {
            Console.WriteLine("Unable to delete the example key: {0}", ex);
        }

        rk.Close();
    }
}

/* This code example produces the following output:

Example key created.

Retrieved value: StringValue

Unable to write to the example key. Caught SecurityException: Requested registry access is not allowed.

Unable to change permissions for the example key. Caught UnauthorizedAccessException: Cannot write to the registry key.

Press Enter to delete the example key.

Example key was deleted.
 */

Комментарии

Используйте перечисление RegistryRights , чтобы указать права доступа к реестру при создании RegistrySecurity объектов. Чтобы применить права доступа к разделу реестра, сначала добавьте RegistryAccessRule объекты в RegistrySecurity объект, а затем присоедините RegistrySecurity объект к ключу с помощью RegistryKey.SetAccessControl метода или соответствующую перегрузку RegistryKey.CreateSubKey метода.

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

Продукт Версии
.NET Core 1.0, Core 1.1, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5

См. также раздел