Was this page helpful?
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

RegistryKey.OpenSubKey Method (String, Boolean)


Retrieves a specified subkey, and specifies whether write access is to be applied to the key.

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

public RegistryKey OpenSubKey(
	string name,
	bool writable


Type: System.String

Name or path of the subkey to open.

Type: System.Boolean

Set to true if you need write access to the key.

Return Value

Type: Microsoft.Win32.RegistryKey

The subkey requested, or null if the operation failed.

Exception Condition

name is null.


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


The user does not have the permissions required to access the registry key in the specified mode.

If the requested key does not exist, this method returns null instead of throwing an exception.

If writable is true, the key will be opened for reading and writing, otherwise, the key will be opened as read-only.

In order to use the OpenSubKey method, you must have an instance of the RegistryKey method. To get an instance of RegistryKey, use one of the static members of the Registry class.

The following code example creates a test key and uses the OpenSubKey method to open it, demonstrating both overloads of the method.

using System;
using Microsoft.Win32;
using Microsoft.VisualBasic;

public class Example
    public static void Main()
        // Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistryOpenSubKeyExample", false);
        RegistryKey rk = Registry.CurrentUser.CreateSubKey("RegistryOpenSubKeyExample");

        // Obtain an instance of RegistryKey for the CurrentUser registry 
        // root. 
        RegistryKey rkCurrentUser = Registry.CurrentUser;

        // Obtain the test key (read-only) and display it.
        RegistryKey rkTest = rkCurrentUser.OpenSubKey("RegistryOpenSubKeyExample");
        Console.WriteLine("Test key: {0}", rkTest);

        // Obtain the test key in one step, using the CurrentUser registry 
        // root.
        rkTest = Registry.CurrentUser.OpenSubKey("RegistryOpenSubKeyExample");
        Console.WriteLine("Test key: {0}", rkTest);

        // Open the test key in read/write mode.
        rkTest = Registry.CurrentUser.OpenSubKey("RegistryOpenSubKeyExample", true);
        rkTest.SetValue("TestName", "TestValue");
        Console.WriteLine("Test value for TestName: {0}", rkTest.GetValue("TestName"));
    } //Main
} //Example


for the ability to read the specified registry key. Associated enumeration: RegistryPermissionAccess.Read


for the ability to access the specified registry key if it is a remote key. Associated enumeration: SecurityPermissionFlag.UnmanagedCode

.NET Framework
Available since 1.1
Return to top
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2015 Microsoft