Export (0) Print
Expand All

RegistryKey.SetAccessControl Method

Note: This method is new in the .NET Framework version 2.0.

Applies Windows access control security to an existing registry key.

Namespace: Microsoft.Win32
Assembly: mscorlib (in mscorlib.dll)

public void SetAccessControl (
	RegistrySecurity registrySecurity
)
public void SetAccessControl (
	RegistrySecurity registrySecurity
)
public function SetAccessControl (
	registrySecurity : RegistrySecurity
)

Parameters

registrySecurity

A RegistrySecurity object that specifies the access control security to apply to the current subkey.

Exception typeCondition

UnauthorizedAccessException

The current RegistryKey object represents a key with access control security, and the caller does not have RegistryRights.ChangePermissions rights.

ArgumentNullException

registrySecurity is a null reference (Nothing in Visual Basic).

ObjectDisposedException

The RegistryKey being manipulated is closed (closed keys cannot be accessed).

To modify permissions for a registry key, use the GetAccessControl method to obtain a RegistrySecurity object representing the existing Windows access control security, modify that RegistrySecurity object, and then use the SetAccessControl method to update security for the key.

Caution noteCaution

The RegistrySecurity object specified for registrySecurity replaces the existing security for the registry key. To add permissions for a new user, use the GetAccessControl method to obtain the existing access control security, and then modify it.

The following code example creates a test key. The current user is allowed ReadKey and Delete rights but denied ChangePermissions and WriteKey rights. Subsequent attempts to manipulate the key succeed or fail depending on these permissions.

Before the key is deleted, the code pauses. You can switch to the registry editor and verify that the same access rights apply when the key is accessed using the registry editor. (This works best if you use RunAs from the command line to run the registry editor and the sample code as a local user without administrator rights. The registry editor always allows an administrator to change permissions, even if the particular administrator has been denied those rights. If you have defined a local user named TestUser, the command runas /user:TestUser cmd opens a command window from which you can run the registry editor and then the sample code.)

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.
 */

import System.*;
import System.Reflection.*;
import System.Security.*;
import System.Security.AccessControl.*;
import Microsoft.Win32.*;

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

        String user = Environment.get_UserDomainName() + "\\" 
            + Environment.get_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 (System.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 (System.Security.SecurityException ex) {
            Console.WriteLine("\r\nUnable to write to the example key." +
                " Caught SecurityException: {0}", ex.get_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 (System.UnauthorizedAccessException ex) {
            Console.WriteLine("\r\nUnable to change permissions for the example key." +
                " Caught UnauthorizedAccessException: {0}", ex.get_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 (System.Exception ex) {
            Console.WriteLine("Unable to delete the example key: {0}", ex);
        }
        rk.Close();
    } //main
} //Example

/* 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.
 */

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft