Export (0) Print
Expand All
6 out of 11 rated this helpful - Rate this topic

RegistryKey Class

Represents a key level node in the Windows registry. This class is a registry encapsulation.

For a list of all members of this type, see RegistryKey Members.

System.Object
   System.MarshalByRefObject
      Microsoft.Win32.RegistryKey

[Visual Basic]
NotInheritable Public Class RegistryKey
   Inherits MarshalByRefObject
   Implements IDisposable
[C#]
public sealed class RegistryKey : MarshalByRefObject, IDisposable
[C++]
public __gc __sealed class RegistryKey : public MarshalByRefObject,
   IDisposable
[JScript]
public class RegistryKey extends MarshalByRefObject implements
   IDisposable

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

The registry acts as a central repository of information for the operating system and the applications on a computer. The registry is organized in a hierarchical format, based on a logical ordering of the elements stored within it (please see Registry for the base-level items in this hierarchy). When storing information in the registry, select the appropriate location based upon the type of information being stored. Be sure to avoid destroying information created by other applications, since this can cause those applications to exhibit unexpected behavior, and can also have an adverse effect upon your own application.

RegistryKeys are the base unit of organization in the registry, and can be compared to folders in Windows Explorer. A particular key can have subkeys (just as a folder can have subfolders), and can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key, or the level directly under the base keys. Each key can also have multiple values associated with it (a value can be compared to a file), which are used to store the information about the application you are interested in. Each value holds one particular piece of information, which can be retrieved or updated when required. For instance, you can create a RegistryKey for your company (under the key HKEY_LOCAL_MACHINE\Software), and then a subkey for each application that your company creates. Each subkey holds the information specific to that application such as color settings, screen location and size, or recognized file extensions.

Note that information stored in the registry is available to other applications and users, and therefore it should not be used to store security, or critical application information.

To get an instance of a RegistryKey, use the static member OpenSubKey, or use the static member of the Registry class.

Example

[Visual Basic, C#, C++] The following code example shows how to create a subkey under HKEY_CURRENT_USER, manipulate the contents, and then delete the subkey.

[Visual Basic] 
Imports Microsoft.VisualBasic
Imports System
Imports System.Security.Permissions
Imports Microsoft.Win32

<Assembly: RegistryPermissionAttribute( _
    SecurityAction.RequestMinimum, All := "HKEY_CURRENT_USER")>

Public Class RegKey
    Shared Sub Main()
    
        ' Create a subkey named Test9999 under HKEY_CURRENT_USER.
        Dim test9999 As RegistryKey = _
            Registry.CurrentUser.CreateSubKey("Test9999")

        ' Create two subkeys under HKEY_CURRENT_USER\Test9999.
        test9999.CreateSubKey("TestName").Close()
        Dim testSettings As RegistryKey = _
            test9999.CreateSubKey("TestSettings")

        ' Create data for the TestSettings subkey.
        testSettings.SetValue("Language", "French")
        testSettings.SetValue("Level", "Intermediate")
        testSettings.SetValue("ID", 123)
        testSettings.SetValue("Password", "Secret")
        testSettings.Close()

        ' Print the information from the Test9999 subkey.
        Console.WriteLine("There are {0} subkeys under Test9999.", _
            test9999.SubKeyCount.ToString())
        For Each subKeyName As String In test9999.GetSubKeyNames()
            Dim tempKey As RegistryKey = _
                test9999.OpenSubKey(subKeyName)
            Console.WriteLine(vbCrLf & "There are {0} values for " & _
                "{1}.", tempKey.ValueCount.ToString(), tempKey.Name)
            For Each valueName As String In tempKey.GetValueNames()
                Console.WriteLine("{0,-8}: {1}", valueName, _
                    tempKey.GetValue(valueName).ToString())
            Next
        Next

        ' Delete the non-secure password value.
        testSettings = test9999.OpenSubKey("TestSettings", True)
        testSettings.DeleteValue("password")

        ' Verify the deletion.
        Console.WriteLine(CType(testSettings.GetValue( _
            "password", "Password not found."), String))
        testSettings.Close()

        ' Delete or close the new subkey.
        Console.Write(vbCrLf & "Delete newly created " & _
            "registry key? (Y/N) ")
        If Char.ToUpper(Convert.ToChar(Console.Read())) = "Y"C Then
            Registry.CurrentUser.DeleteSubKeyTree("Test9999")
            Console.WriteLine(vbCrLf & "Registry key {0} deleted.", _
                test9999.Name)
        Else
            Console.WriteLine(vbCrLf & "Registry key {0} closed.", _
                test9999.ToString())
            test9999.Close()
        End If
   
    End Sub
End Class

[C#] 
using System;
using System.Security.Permissions;
using Microsoft.Win32;

[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum,
    All = "HKEY_CURRENT_USER")]

class RegKey
{
    static void Main()
    {
        // Create a subkey named Test9999 under HKEY_CURRENT_USER.
        RegistryKey test9999 = 
            Registry.CurrentUser.CreateSubKey("Test9999");
        // Create two subkeys under HKEY_CURRENT_USER\Test9999. The
        // keys are disposed when execution exits the using statement.
        using(RegistryKey 
            testName = test9999.CreateSubKey("TestName"),
            testSettings = test9999.CreateSubKey("TestSettings"))
        {
            // Create data for the TestSettings subkey.
            testSettings.SetValue("Language", "French");
            testSettings.SetValue("Level", "Intermediate");
            testSettings.SetValue("ID", 123);
            testSettings.SetValue("Password", "Secret");
        }

        // Print the information from the Test9999 subkey.
        Console.WriteLine("There are {0} subkeys under {1}.", 
            test9999.SubKeyCount.ToString(), test9999.Name);
        foreach(string subKeyName in test9999.GetSubKeyNames())
        {
            using(RegistryKey 
                tempKey = test9999.OpenSubKey(subKeyName))
            {
                Console.WriteLine("\nThere are {0} values for {1}.", 
                    tempKey.ValueCount.ToString(), tempKey.Name);
                foreach(string valueName in tempKey.GetValueNames())
                {
                    Console.WriteLine("{0,-8}: {1}", valueName, 
                        tempKey.GetValue(valueName).ToString());
                }
            }
        }

        using(RegistryKey 
            testSettings = test9999.OpenSubKey("TestSettings", true))
        {
            // Delete the non-secure password value.
            testSettings.DeleteValue("password");

            // Verify the deletion.
            Console.WriteLine((string)testSettings.GetValue(
                "password", "Password not found."));
        }

        // Delete or close the new subkey.
        Console.Write("\nDelete newly created registry key? (Y/N) ");
        if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y')
        {
            Registry.CurrentUser.DeleteSubKeyTree("Test9999");
            Console.WriteLine("\nRegistry key {0} deleted.", 
                test9999.Name);
        }
        else
        {
            Console.WriteLine("\nRegistry key {0} closed.", 
                test9999.ToString());
            test9999.Close();
        }
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Security::Permissions;
using namespace Microsoft::Win32;

[assembly: RegistryPermissionAttribute(SecurityAction::RequestMinimum,
    All = S"HKEY_CURRENT_USER")];

void main()
{
    // Create a subkey named Test9999 under HKEY_CURRENT_USER.
    RegistryKey* test9999 = 
        Registry::CurrentUser->CreateSubKey(S"Test9999");

    // Create two subkeys under HKEY_CURRENT_USER\Test9999.
    test9999->CreateSubKey(S"TestName")->Close();
    RegistryKey* testSettings = 
        test9999->CreateSubKey(S"TestSettings");

    // Create data for the TestSettings subkey.
    testSettings->SetValue(S"Language", S"French");
    testSettings->SetValue(S"Level", S"Intermediate");
    testSettings->SetValue(S"ID", __box(123));
    testSettings->SetValue(S"Password", S"Secret");
    testSettings->Close();

    // Print the information from the Test9999 subkey.
    Console::WriteLine(S"There are {0} subkeys under Test9999.", 
        test9999->SubKeyCount.ToString());
    String* subKeyNames __gc [] = test9999->GetSubKeyNames();
    for(int i =0; i < subKeyNames->Length; i++)
    {
        RegistryKey* tempKey = test9999->OpenSubKey(subKeyNames[i]);
        Console::WriteLine(S"\nThere are {0} values for {1}.", 
            tempKey->ValueCount.ToString(), tempKey->Name);
        String* valueNames __gc [] = tempKey->GetValueNames();
        for(int j = 0; j < valueNames->Length; j++)
        {
            Console::WriteLine(S"{0,-8}: {1}", valueNames[j], 
                tempKey->GetValue(valueNames[j])->ToString());
        }
    }

    // Delete the non-secure password value.
    testSettings = test9999->OpenSubKey(S"TestSettings", true);
    testSettings->DeleteValue(S"password");

    // Verify the deletion.
    Console::WriteLine(dynamic_cast<String*>(
        testSettings->GetValue("password", S"Password not found.")));
    testSettings->Close();

    // Delete or close the new subkey.
    Console::Write(S"\nDelete newly created registry key? (Y/N) ");
    if(Char::ToUpper(Convert::ToChar(Console::Read())) == 'Y')
    {
        Registry::CurrentUser->DeleteSubKeyTree(S"Test9999");
        Console::WriteLine(S"\nRegistry key {0} deleted.", 
            test9999->Name);
    }
    else
    {
        Console::WriteLine(S"\nRegistry key {0} closed.", 
            test9999->ToString());
        test9999->Close();
    }
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: Microsoft.Win32

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: Mscorlib (in Mscorlib.dll)

See Also

RegistryKey Members | Microsoft.Win32 Namespace | Registry | RegistryHive

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.