RegistryKey 类

定义

表示 Windows 注册表中的项级节点。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
继承
继承
RegistryKey
属性
实现

示例

下面的代码示例演示如何在 HKEY_CURRENT_USER 下创建一个子项,操作其内容,然后删除该子项。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

注解

若要获取的实例 RegistryKey ,请使用类的静态成员之一 RegistryTo 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. 注册表以分层格式组织,基于其中存储的元素的逻辑排序 (请参阅 Registry 此层次结构中的基本级别项) 。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.

重要

此类型实现 IDisposable 接口。This type implements the IDisposable interface. 在使用完类型后,您应直接或间接释放类型。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接释放类型,请在 try/catch 块中调用其 Dispose 方法。To dispose of the type directly, call its Dispose method in a try/catch block. 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。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. 例如,你可以 RegistryKey 在密钥 HKEY_LOCAL_MACHINE \software 下为公司创建,然后为公司创建的每个应用程序创建一个子项。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.

注意

不要 RegistryKey 以这样的方式公开对象:恶意程序可能会创建数千个无意义子项或键/值对。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.

从开始 .NET Framework 4.NET Framework 4 ,注册表项的长度不再限制为255个字符。Starting in the .NET Framework 4.NET Framework 4, the length of a registry key is no longer limited to 255 characters.

属性

Handle

获取一个 SafeRegistryHandle 对象,该对象表示当前 RegistryKey 对象封装的注册表项。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.

方法

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.

(继承自 MarshalByRefObject)
CreateSubKey(String)

创建一个新子项或打开一个现有子项以进行写访问。Creates a new subkey or opens an existing subkey for write access.

CreateSubKey(String, Boolean)

创建一个新子项或打开具有指定访问权限的现有子项。Creates a new subkey or opens an existing subkey with the specified access. 从 .NET Framework 4.6 开始可用。Available starting with .NET Framework 4.6.

CreateSubKey(String, Boolean, RegistryOptions)

创建一个新子项或打开具有指定访问权限的现有子项。Creates a new subkey or opens an existing subkey with the specified access. 从 .NET Framework 4.6 开始可用。Available starting with .NET Framework 4.6.

CreateSubKey(String, RegistryKeyPermissionCheck)

使用指定的权限检查选项创建一个新子项或打开一个现有子项以进行写访问。Creates a new subkey or opens an existing subkey for write access, using the specified permission check option.

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, 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, RegistrySecurity)

使用指定的权限检查选项和注册表安全性创建一个新子项或打开一个现有子项以进行写访问。Creates a new subkey or opens an existing subkey for write access, using the specified permission check option and registry security.

DeleteSubKey(String)

删除指定子项。Deletes the specified subkey.

DeleteSubKey(String, Boolean)

删除指定的子项,并指定在找不到该子项时是否引发异常。Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found.

DeleteSubKeyTree(String)

递归删除子项和任何子级子项。Deletes a subkey and any child subkeys recursively.

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.

DeleteValue(String)

从此项中删除指定值。Deletes the specified value from this key.

DeleteValue(String, Boolean)

从此项中删除指定的值,并指定在找不到该值时是否引发异常。Deletes the specified value from this key, and specifies whether an exception is raised if the value is not found.

Dispose()

释放 RegistryKey 类的当前实例所使用的所有资源。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.

(继承自 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)

根据指定的句柄创建注册表项。Creates a registry key from a specified handle.

FromHandle(SafeRegistryHandle, RegistryView)

利用指定的句柄和注册表视图设置创建注册表项。Creates a registry key from a specified handle and registry view setting.

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.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetSubKeyNames()

检索包含所有子项名称的字符串数组。Retrieves an array of strings that contains all the subkey names.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
GetValue(String)

检索与指定名称关联的值。Retrieves the value associated with the specified name. 如果注册表中不存在名称/值对,则返回 nullReturns null if the name/value pair does not exist in the registry.

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, 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.

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()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
OpenBaseKey(RegistryHive, RegistryView)

打开一个新的 RegistryKey,它使用指定的视图在本地计算机上表示请求的项。Opens a new RegistryKey that represents the requested key on the local machine with the specified view.

OpenRemoteBaseKey(RegistryHive, String)

打开一个新的 RegistryKey,它表示远程计算机上的请求的项。Opens a new RegistryKey that represents the requested key on a remote machine.

OpenRemoteBaseKey(RegistryHive, String, RegistryView)

打开一个新的注册表项,它使用指定的视图在远程计算机上表示请求的项。Opens a new registry key that represents the requested key on a remote machine with the specified view.

OpenSubKey(String)

以只读方式检索子项。Retrieves a subkey as read-only.

OpenSubKey(String, Boolean)

检索指定的子项,并指定是否将写访问权限应用于该项。Retrieves a specified subkey, and specifies whether write access is to be applied to the key.

OpenSubKey(String, RegistryKeyPermissionCheck)

检索指定的子项以进行读取或读/写访问。Retrieves the specified subkey for read or read/write access.

OpenSubKey(String, RegistryKeyPermissionCheck, RegistryRights)

检索指定的子项以进行读取或读/写访问,请求指定的访问权限。Retrieves the specified subkey for read or read/write access, requesting the specified access rights.

OpenSubKey(String, RegistryRights)

检索具有指定名称和访问权限的子项。Retrieves a subkey with the specified name and access rights. 从 .NET Framework 4.6 开始可用。Available starting with .NET Framework 4.6.

SetAccessControl(RegistrySecurity)

向现有注册表项应用 Windows 访问控制安全性。Applies Windows access control security to an existing registry key.

SetValue(String, Object)

设置指定的名称/值对。Sets the specified name/value pair.

SetValue(String, Object, RegistryValueKind)

使用指定的注册表数据类型设置注册表项中的名称/值对的值。Sets the value of a name/value pair in the registry key, using the specified registry data type.

ToString()

检索此项的字符串表示形式。Retrieves a string representation of this key.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

显式接口实现

IDisposable.Dispose()

此 API 支持产品基础结构,不能在代码中直接使用。

对当前密钥执行 Close()Performs a Close() on the current key.

扩展方法

GetAccessControl(RegistryKey)

返回注册表项的安全信息。Returns the security information of a registry key.

GetAccessControl(RegistryKey, AccessControlSections)

返回注册表项的安全信息。Returns the security information of a registry key.

SetAccessControl(RegistryKey, RegistrySecurity)

更改现有注册表项的安全特性。Changes the security attributes of an existing registry key.

适用于

另请参阅