Szerkesztés

Megosztás a következőn keresztül:


RegistryKey Class

Definition

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

public ref class RegistryKey sealed : MarshalByRefObject, IDisposable
public ref class RegistryKey sealed : IDisposable
public sealed class RegistryKey : MarshalByRefObject, IDisposable
public sealed class RegistryKey : IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class RegistryKey : MarshalByRefObject, IDisposable
type RegistryKey = class
    inherit MarshalByRefObject
    interface IDisposable
type RegistryKey = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type RegistryKey = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class RegistryKey
Inherits MarshalByRefObject
Implements IDisposable
Public NotInheritable Class RegistryKey
Implements IDisposable
Inheritance
Inheritance
RegistryKey
Attributes
Implements

Examples

The following code example shows how to create a subkey under HKEY_CURRENT_USER, manipulate its contents, and then delete the subkey.

using namespace System;
using namespace System::Security::Permissions;
using namespace Microsoft::Win32;

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

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

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

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

      }
   }
   
   // Delete the ID value.
   testSettings = test9999->OpenSubKey( "TestSettings", true );
   testSettings->DeleteValue( "id" );

   // Verify the deletion.
   Console::WriteLine( dynamic_cast<String^>(testSettings->GetValue(  "id", "ID not found." )) );
   testSettings->Close();

   // 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();
   }
}
using System;
using System.Security.Permissions;
using Microsoft.Win32;

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);
        }

        // 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 ID value.
            testSettings.DeleteValue("id");

            // Verify the deletion.
            Console.WriteLine((string)testSettings.GetValue(
                "id", "ID 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();
        }
    }
}
Imports System.Security.Permissions
Imports Microsoft.Win32

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.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 ID value.
        testSettings = test9999.OpenSubKey("TestSettings", True)
        testSettings.DeleteValue("id")

        ' Verify the deletion.
        Console.WriteLine(CType(testSettings.GetValue( _
            "id", "ID 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

Remarks

To get an instance of RegistryKey, use one of the static members of the Registry class.

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 on the type of information being stored. Be sure to avoid destroying information created by other applications, because this can cause those applications to exhibit unexpected behavior, and can also have an adverse effect upon your own application.

Important

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

Registry keys are the base unit of organization in the registry, and can be compared to folders in File Explorer. A particular key can have subkeys, just as a folder can have subfolders. Each key can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key or at 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 - for example, information about an application installed on the computer. 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 should not be used to store security data or critical application information.

Caution

Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. For example, do not allow callers to enter arbitrary keys or values.

Starting in the .NET Framework 4, the length of a registry key is no longer limited to 255 characters.

Properties

Handle

Gets a SafeRegistryHandle object that represents the registry key that the current RegistryKey object encapsulates.

Name

Retrieves the name of the key.

SubKeyCount

Retrieves the count of subkeys of the current key.

ValueCount

Retrieves the count of values in the key.

View

Gets the view that was used to create the registry key.

Methods

Close()

Closes the key and flushes it to disk if its contents have been modified.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
CreateSubKey(String, Boolean, RegistryOptions)

Creates a new subkey or opens an existing subkey with the specified access. Available starting with .NET Framework 4.6.

CreateSubKey(String, Boolean)

Creates a new subkey or opens an existing subkey with the specified access. Available starting with .NET Framework 4.6.

CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions, RegistrySecurity)

Creates a subkey or opens a subkey for write access, using the specified permission check option, registry option, and registry security.

CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions)

Creates a subkey or opens a subkey for write access, using the specified permission check and registry options.

CreateSubKey(String, RegistryKeyPermissionCheck, RegistrySecurity)

Creates a new subkey or opens an existing subkey for write access, using the specified permission check option and registry security.

CreateSubKey(String, RegistryKeyPermissionCheck)

Creates a new subkey or opens an existing subkey for write access, using the specified permission check option.

CreateSubKey(String)

Creates a new subkey or opens an existing subkey for write access.

DeleteSubKey(String, Boolean)

Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found.

DeleteSubKey(String)

Deletes the specified subkey.

DeleteSubKeyTree(String, Boolean)

Deletes the specified subkey and any child subkeys recursively, and specifies whether an exception is raised if the subkey is not found.

DeleteSubKeyTree(String)

Deletes a subkey and any child subkeys recursively.

DeleteValue(String, Boolean)

Deletes the specified value from this key, and specifies whether an exception is raised if the value is not found.

DeleteValue(String)

Deletes the specified value from this key.

Dispose()

Releases all resources used by the current instance of the RegistryKey class.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

Closes the key and flushes it to disk if the contents have been modified.

Flush()

Writes all the attributes of the specified open registry key into the registry.

FromHandle(SafeRegistryHandle, RegistryView)

Creates a registry key from a specified handle and registry view setting.

FromHandle(SafeRegistryHandle)

Creates a registry key from a specified handle.

GetAccessControl()

Returns the access control security for the current registry key.

GetAccessControl(AccessControlSections)

Returns the specified sections of the access control security for the current registry key.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetSubKeyNames()

Retrieves an array of strings that contains all the subkey names.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetValue(String, Object, RegistryValueOptions)

Retrieves the value associated with the specified name and retrieval options. If the name is not found, returns the default value that you provide.

GetValue(String, Object)

Retrieves the value associated with the specified name. If the name is not found, returns the default value that you provide.

GetValue(String)

Retrieves the value associated with the specified name. Returns null if the name/value pair does not exist in the registry.

GetValueKind(String)

Retrieves the registry data type of the value associated with the specified name.

GetValueNames()

Retrieves an array of strings that contains all the value names associated with this key.

InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OpenBaseKey(RegistryHive, RegistryView)

Opens a new RegistryKey that represents the requested key on the local machine with the specified view.

OpenRemoteBaseKey(RegistryHive, String, RegistryView)

Opens a new registry key that represents the requested key on a remote machine with the specified view.

OpenRemoteBaseKey(RegistryHive, String)

Opens a new RegistryKey that represents the requested key on a remote machine.

OpenSubKey(String, Boolean)

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

OpenSubKey(String, RegistryKeyPermissionCheck, RegistryRights)

Retrieves the specified subkey for read or read/write access, requesting the specified access rights.

OpenSubKey(String, RegistryKeyPermissionCheck)

Retrieves the specified subkey for read or read/write access.

OpenSubKey(String, RegistryRights)

Retrieves a subkey with the specified name and access rights. Available starting with .NET Framework 4.6.

OpenSubKey(String)

Retrieves a subkey as read-only.

SetAccessControl(RegistrySecurity)

Applies Windows access control security to an existing registry key.

SetValue(String, Object, RegistryValueKind)

Sets the value of a name/value pair in the registry key, using the specified registry data type.

SetValue(String, Object)

Sets the specified name/value pair.

ToString()

Retrieves a string representation of this key.

Explicit Interface Implementations

IDisposable.Dispose()

This API supports the product infrastructure and is not intended to be used directly from your code.

Performs a Close() on the current key.

Extension Methods

GetAccessControl(RegistryKey, AccessControlSections)

Returns the security information of a registry key.

GetAccessControl(RegistryKey)

Returns the security information of a registry key.

SetAccessControl(RegistryKey, RegistrySecurity)

Changes the security attributes of an existing registry key.

Applies to

See also