Registry 类

定义

提供表示 Windows 注册表中的根项的 RegistryKey 对象,并提供访问项/值对的 static 方法。Provides RegistryKey objects that represent the root keys in the Windows registry, and static methods to access key/value pairs.

public ref class Registry abstract sealed
[System.Runtime.InteropServices.ComVisible(true)]
public static class Registry
type Registry = class
Public Class Registry
继承
Registry
属性

示例

本部分包含两个代码示例。This section contains two code examples. 第一个示例演示根项,第二个示例演示staticGetValueSetValue方法。The first example demonstrates root keys, and the second example demonstrates the staticGetValue and SetValue methods.

示例 1Example 1

下面的代码示例演示如何检索的 HKEY_USERS 项、 子项和打印它们在屏幕上的名称。The following code example demonstrates how to retrieve the subkeys of the HKEY_USERS key, and print their names to the screen. 使用OpenSubKey方法来创建感兴趣的特定子项的一个实例。Use the OpenSubKey method to create an instance of the particular subkey of interest. 然后,可以使用中的其他操作RegistryKey来操作该注册表项。You can then use other operations in RegistryKey to manipulate that key.

using namespace System;
using namespace Microsoft::Win32;
void PrintKeys( RegistryKey ^ rkey )
{
   
   // Retrieve all the subkeys for the specified key.
   array<String^>^names = rkey->GetSubKeyNames();
   int icount = 0;
   Console::WriteLine( "Subkeys of {0}", rkey->Name );
   Console::WriteLine( "-----------------------------------------------" );
   
   // Print the contents of the array to the console.
   System::Collections::IEnumerator^ enum0 = names->GetEnumerator();
   while ( enum0->MoveNext() )
   {
      String^ s = safe_cast<String^>(enum0->Current);
      Console::WriteLine( s );
      
      // The following code puts a limit on the number
      // of keys displayed.  Comment it out to print the
      // complete list.
      icount++;
      if ( icount >= 10 )
            break;
   }
}

int main()
{
   
   // Create a RegistryKey, which will access the HKEY_USERS
   // key in the registry of this machine.
   RegistryKey ^ rk = Registry::Users;
   
   // Print out the keys.
   PrintKeys( rk );
}

using System;
using Microsoft.Win32;

class Reg {
    public static void Main() {

        // Create a RegistryKey, which will access the HKEY_USERS
        // key in the registry of this machine.
        RegistryKey rk = Registry.Users;

        // Print out the keys.
        PrintKeys(rk);
    }

    static void PrintKeys(RegistryKey rkey) {

        // Retrieve all the subkeys for the specified key.
        String [] names = rkey.GetSubKeyNames();

        int icount = 0;

        Console.WriteLine("Subkeys of " + rkey.Name);
        Console.WriteLine("-----------------------------------------------");

        // Print the contents of the array to the console.
        foreach (String s in names) {
            Console.WriteLine(s);

            // The following code puts a limit on the number
            // of keys displayed.  Comment it out to print the
            // complete list.
            icount++;
            if (icount >= 10)
                break;
        }
    }
}
Imports Microsoft.Win32

Class Reg
    
    Public Shared Sub Main()
        
        ' Create a RegistryKey, which will access the HKEY_USERS
        ' key in the registry of this machine.
        Dim rk As RegistryKey = Registry.Users
        
        ' Print out the keys.
        PrintKeys(rk)
    End Sub    
    
    Shared Sub PrintKeys(rkey As RegistryKey)
        
        ' Retrieve all the subkeys for the specified key.
        Dim names As String() = rkey.GetSubKeyNames()
        
        Dim icount As Integer = 0
        
        Console.WriteLine("Subkeys of " & rkey.Name)
        Console.WriteLine("-----------------------------------------------")
        
        ' Print the contents of the array to the console.
        Dim s As String
        For Each s In  names
            Console.WriteLine(s)
            
            ' The following code puts a limit on the number
            ' of keys displayed.  Comment it out to print the
            ' complete list.
            icount += 1            
            If icount >= 10 Then
                Exit For
            End If
        Next s
    End Sub
End Class

示例 2Example 2

下面的代码示例将多个数据类型的值存储在一个示例密钥,创建密钥,因为它会检索并显示的值。The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. 该示例演示如何存储和检索默认 (无名) 的名称/值对,以及如何使用defaultValue不存在名称/值对时。The example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.

using namespace System;
using namespace Microsoft::Win32;

int main()
{   
    // The name of the key must include a valid root.
    String^ userRoot = "HKEY_CURRENT_USER";
    String^ subKey = "RegistrySetValueExample2";
    String^ keyName = String::Concat(userRoot, "\\", subKey);
    
    // An int value can be stored without specifying the
    // registry data type, but Int64 values will be stored
    // as strings unless you specify the type. Note that
    // the int is stored in the default name/value
    // pair.
    Registry::SetValue(keyName, "", 5280);
    Registry::SetValue(keyName, "TestInt64", 12345678901234, 
        RegistryValueKind::QWord);
    
    // Strings with expandable environment variables are
    // stored as ordinary strings unless you specify the
    // data type.
    Registry::SetValue(keyName, "TestExpand", "My path: %path%");
    Registry::SetValue(keyName, "TestExpand2", "My path: %path%", 
        RegistryValueKind::ExpandString);
    
    // Arrays of strings are stored automatically as 
    // MultiString. Similarly, arrays of Byte are stored
    // automatically as Binary.
    array<String^>^ strings  = {"One", "Two", "Three"};
    Registry::SetValue(keyName, "TestArray", strings);
    
    // Your default value is returned if the name/value pair
    // does not exist.
    String^ noSuch = (String^)Registry::GetValue(keyName, 
        "NoSuchName", 
        "Return this default if NoSuchName does not exist.");
    Console::WriteLine("\r\nNoSuchName: {0}", noSuch);
    
    // Retrieve the int and Int64 values, specifying 
    // numeric default values in case the name/value pairs
    // do not exist. The int value is retrieved from the
    // default (nameless) name/value pair for the key.
    int testInteger = (int)Registry::GetValue(keyName, "", -1);
    Console::WriteLine("(Default): {0}", testInteger);
    long long testInt64 = (long long)Registry::GetValue(keyName, 
        "TestInt64", System::Int64::MinValue);
    Console::WriteLine("TestInt64: {0}", testInt64);
    
    // When retrieving a MultiString value, you can specify
    // an array for the default return value. 
    array<String^>^ testArray = (array<String^>^)Registry::GetValue(
        keyName, "TestArray", 
        gcnew array<String^> {"Default if TestArray does not exist."});
    for (int i = 0; i < testArray->Length; i++)
    {
        Console::WriteLine("TestArray({0}): {1}", i, testArray[i]);
    }
    
    // A string with embedded environment variables is not
    // expanded if it was stored as an ordinary string.
    String^ testExpand = (String^)Registry::GetValue(keyName, 
        "TestExpand", "Default if TestExpand does not exist.");
    Console::WriteLine("TestExpand: {0}", testExpand);
    
    // A string stored as ExpandString is expanded.
    String^ testExpand2 = (String^)Registry::GetValue(keyName, 
        "TestExpand2", "Default if TestExpand2 does not exist.");
    Console::WriteLine(
        "TestExpand2: {0}...", testExpand2->Substring(0, 40));
    Console::WriteLine(
        "\r\nUse the registry editor to examine the key.");
    Console::WriteLine("Press the Enter key to delete the key.");
    Console::ReadLine();
    Registry::CurrentUser->DeleteSubKey(subKey);
}
//
// This code example produces output similar to the following:
//
// NoSuchName: Return this default if NoSuchName does not exist.
// (Default): 5280
// TestInt64: 12345678901234
// TestArray(0): One
// TestArray(1): Two
// TestArray(2): Three
// TestExpand: My path: %path%
// TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
// Use the registry editor to examine the key.
// Press the Enter key to delete the key.
using System;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // The name of the key must include a valid root.
        const string userRoot = "HKEY_CURRENT_USER";
        const string subkey = "RegistrySetValueExample";
        const string keyName = userRoot + "\\" + subkey;

        // An int value can be stored without specifying the
        // registry data type, but long values will be stored
        // as strings unless you specify the type. Note that
        // the int is stored in the default name/value
        // pair.
        Registry.SetValue(keyName, "", 5280);
        Registry.SetValue(keyName, "TestLong", 12345678901234,
            RegistryValueKind.QWord);

        // Strings with expandable environment variables are
        // stored as ordinary strings unless you specify the
        // data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%");
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%",
            RegistryValueKind.ExpandString);

        // Arrays of strings are stored automatically as 
        // MultiString. Similarly, arrays of Byte are stored
        // automatically as Binary.
        string[] strings = {"One", "Two", "Three"};
        Registry.SetValue(keyName, "TestArray", strings);

        // Your default value is returned if the name/value pair
        // does not exist.
        string noSuch = (string) Registry.GetValue(keyName, 
            "NoSuchName",
            "Return this default if NoSuchName does not exist.");
        Console.WriteLine("\r\nNoSuchName: {0}", noSuch);

        // Retrieve the int and long values, specifying 
        // numeric default values in case the name/value pairs
        // do not exist. The int value is retrieved from the
        // default (nameless) name/value pair for the key.
        int tInteger = (int) Registry.GetValue(keyName, "", -1);
        Console.WriteLine("(Default): {0}", tInteger);
        long tLong = (long) Registry.GetValue(keyName, "TestLong",
            long.MinValue);
        Console.WriteLine("TestLong: {0}", tLong);

        // When retrieving a MultiString value, you can specify
        // an array for the default return value. 
        string[] tArray = (string[]) Registry.GetValue(keyName,
            "TestArray",
            new string[] {"Default if TestArray does not exist."});
        for(int i=0; i<tArray.Length; i++)
        {
            Console.WriteLine("TestArray({0}): {1}", i, tArray[i]);
        }

        // A string with embedded environment variables is not
        // expanded if it was stored as an ordinary string.
        string tExpand = (string) Registry.GetValue(keyName,
             "TestExpand", 
             "Default if TestExpand does not exist.");
        Console.WriteLine("TestExpand: {0}", tExpand);

        // A string stored as ExpandString is expanded.
        string tExpand2 = (string) Registry.GetValue(keyName,
            "TestExpand2",
            "Default if TestExpand2 does not exist.");
        Console.WriteLine("TestExpand2: {0}...",
            tExpand2.Substring(0, 40));

        Console.WriteLine("\r\nUse the registry editor to examine the key.");
        Console.WriteLine("Press the Enter key to delete the key.");
        Console.ReadLine();
        Registry.CurrentUser.DeleteSubKey(subkey);
    }
}
//
// This code example produces output similar to the following:
//
//NoSuchName: Return this default if NoSuchName does not exist.
//(Default): 5280
//TestLong: 12345678901234
//TestArray(0): One
//TestArray(1): Two
//TestArray(2): Three
//TestExpand: My path: %path%
//TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
//Use the registry editor to examine the key.
//Press the Enter key to delete the key.
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' The name of the key must include a valid root.
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "RegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        ' Integer values can be stored without specifying the
        ' registry data type, but Long values will be stored
        ' as strings unless you specify the type. Note that
        ' the integer is stored in the default name/value
        ' pair.
        Registry.SetValue(keyName, "", 5280)
        Registry.SetValue(keyName, "TestLong", 12345678901234, _
            RegistryValueKind.QWord)

        ' Strings with expandable environment variables are
        ' stored as ordinary strings unless you specify the
        ' data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%")
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%", _
            RegistryValueKind.ExpandString)

        ' Arrays of strings are stored automatically as 
        ' MultiString. Similarly, arrays of Byte are stored
        ' automatically as Binary.
        Dim strings() As String = {"One", "Two", "Three"}
        Registry.SetValue(keyName, "TestArray", strings)

        ' Your default value is returned if the name/value pair
        ' does not exist.
        Dim noSuch As String = _
            Registry.GetValue(keyName, "NoSuchName", _
            "Return this default if NoSuchName does not exist.")
        Console.WriteLine(vbCrLf & "NoSuchName: {0}", noSuch)

        ' Retrieve the Integer and Long values, specifying 
        ' numeric default values in case the name/value pairs
        ' do not exist. The Integer value is retrieved from the
        ' default (nameless) name/value pair for the key.
        Dim tInteger As Integer = _
            Registry.GetValue(keyName, "", -1)
        Console.WriteLine("(Default): {0}", tInteger)
        Dim tLong As Long = Registry.GetValue(keyName, _
             "TestLong", Long.MinValue)
        Console.WriteLine("TestLong: {0}", tLong)

        ' When retrieving a MultiString value, you can specify
        ' an array for the default return value. The value is
        ' declared inline, but could also be declared as:
        ' Dim default() As String = {"Default value."}
        '
        Dim tArray() As String = _
            Registry.GetValue(keyName, "TestArray", _
            New String() {"Default if TestArray does not exist."})
        For i As Integer = 0 To tArray.Length - 1
            Console.WriteLine("TestArray({0}): {1}", i, tArray(i))
        Next

        ' A string with embedded environment variables is not
        ' expanded if it was stored as an ordinary string.
        Dim tExpand As String = Registry.GetValue(keyName, _
             "TestExpand", "Default if TestExpand does not exist.")
        Console.WriteLine("TestExpand: {0}", tExpand)

        ' A string stored as ExpandString is expanded.
        Dim tExpand2 As String = Registry.GetValue(keyName, _
             "TestExpand2", "Default if TestExpand2 does not exist.")
        Console.WriteLine("TestExpand2: {0}...", _
            tExpand2.Substring(0, 40))

        Console.WriteLine(vbCrLf & _
            "Use the registry editor to examine the key.")
        Console.WriteLine("Press the Enter key to delete the key.")
        Console.ReadLine()
        Registry.CurrentUser.DeleteSubKey(subkey)
    End Sub
End Class
'
' This code example produces output similar to the following:
'
'NoSuchName: Return this default if NoSuchName does not exist.
'(Default): 5280
'TestLong: 12345678901234
'TestArray(0): One
'TestArray(1): Two
'TestArray(2): Three
'TestExpand: My path: %path%
'TestExpand2: My path: D:\Program Files\Microsoft.NET\...
'
'Use the registry editor to examine the key.
'Press the Enter key to delete the key.

注解

此类提供在运行 Windows 的计算机上的注册表中找到的标准的根键集。This class provides the set of standard root keys found in the registry on machines running Windows. 注册表是有关应用程序、 用户和默认的系统设置的信息存储设施。The registry is a storage facility for information about applications, users, and default system settings. 例如,应用程序可以使用注册表来存储需要关闭应用程序后, 保留的信息以及重新加载应用程序时访问相同的信息。For example, applications can use the registry for storing information that needs to be preserved after the application is closed, and access that same information when the application is reloaded. 例如,可以将颜色首选项、 屏幕位置或窗口的大小。For instance, you can store color preferences, screen locations, or the size of the window. 可以通过将信息存储在注册表中的其他位置来控制此数据为每个用户。You can control this data for each user by storing the information in a different location in the registry.

基本或根RegistryKey实例公开的Registry类描述子项和注册表中的值的基本存储机制。The base, or root RegistryKey instances that are exposed by the Registry class delineate the basic storage mechanism for subkeys and values in the registry. 所有键都是只读的因为注册表取决于其存在。All keys are read-only because the registry depends on their existence. 公开的项Registry是:The keys exposed by Registry are:

CurrentUser
存储用户首选项有关的信息。Stores information about user preferences.

LocalMachine
存储在本地计算机的配置信息。Stores configuration information for the local machine.

ClassesRoot
类型 (和类) 的相关信息存储和其属性。Stores information about types (and classes) and their properties.

Users
存储有关默认用户配置的信息。Stores information about the default user configuration.

PerformanceData
存储的软件组件的性能信息。Stores performance information for software components.

CurrentConfig
存储非用户特定的硬件信息。Stores non-user-specific hardware information.

DynData
将动态数据存储。Stores dynamic data.

一旦您确定要在其下存储/检索信息从注册表根项,可以使用RegistryKey类来添加或删除子项,并处理给定密钥的值。Once you have identified the root key under which you want to store/retrieve information from the registry, you can use the RegistryKey class to add or remove subkeys, and manipulate the values for a given key.

硬件设备可以将信息放在自动使用插接口注册表中。Hardware devices can place information in the registry automatically using the Plug and Play interface. 安装设备驱动程序软件可以通过写入到标准 Api 在注册表中放的信息。Software for installing device drivers can place information in the registry by writing to standard APIs.

用于获取和设置值的静态方法Static Methods for Getting and Setting Values

在.NET Framework 2.0 版中,Registry类还包含staticGetValueSetValue用于设置和检索从注册表项值的方法。In the .NET Framework version 2.0, the Registry class also contains staticGetValue and SetValue methods for setting and retrieving values from registry keys. 这些方法打开和关闭注册表项的每个它们使用,因此它们不会执行的时间以及中的类似方法RegistryKey类,当您访问大量的值。These methods open and close registry keys each time they are used, so they do not perform as well as analogous methods in the RegistryKey class, when you access a large number of values.

RegistryKey类还提供了可以设置注册表项,来检索它之前, 测试一个值的数据类型和删除项的 Windows 访问控制安全性的方法。The RegistryKey class also provides methods that allow you to set Windows access control security for registry keys, to test the data type of a value before retrieving it, and to delete keys.

字段

ClassesRoot

定义文档的类型(或类)以及与那些类型关联的属性。Defines the types (or classes) of documents and the properties associated with those types. 该字段读取 Windows 注册表基项 HKEY_CLASSES_ROOT。This field reads the Windows registry base key HKEY_CLASSES_ROOT.

CurrentConfig

包含有关非用户特定的硬件的配置信息。Contains configuration information pertaining to the hardware that is not specific to the user. 该字段读取 Windows 注册表基项 HKEY_CURRENT_CONFIG。This field reads the Windows registry base key HKEY_CURRENT_CONFIG.

CurrentUser

包含有关当前用户首选项的信息。Contains information about the current user preferences. 此字段读取 Windows 注册表基项 HKEY_CURRENT_USER。This field reads the Windows registry base key HKEY_CURRENT_USER.

DynData

包含动态注册表数据。Contains dynamic registry data. 该字段读取 Windows 注册表基项 HKEY_DYN_DATA。This field reads the Windows registry base key HKEY_DYN_DATA.

LocalMachine

包含本地计算机的配置数据。Contains the configuration data for the local machine. 该字段读取 Windows 注册表基项 HKEY_LOCAL_MACHINE。This field reads the Windows registry base key HKEY_LOCAL_MACHINE.

PerformanceData

包含软件组件的性能信息。Contains performance information for software components. 该字段读取 Windows 注册表基项 HKEY_PERFORMANCE_DATA。This field reads the Windows registry base key HKEY_PERFORMANCE_DATA.

Users

包含有关默认用户配置的信息。Contains information about the default user configuration. 该字段读取 Windows 注册表基项 HKEY_USERS。This field reads the Windows registry base key HKEY_USERS.

方法

GetValue(String, String, Object)

检索与指定的注册表项中的指定名称关联的值。Retrieves the value associated with the specified name, in the specified registry key. 如果在指定的项中未找到该名称,则返回您提供的默认值;或者,如果指定的项不存在,则返回 nullIf the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.

SetValue(String, String, Object)

设置指定的注册表项的指定名称/值对。Sets the specified name/value pair on the specified registry key. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

SetValue(String, String, Object, RegistryValueKind)

通过使用指定的注册表数据类型,设置该指定的注册表项的名称/值对。Sets the name/value pair on the specified registry key, using the specified registry data type. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

适用于

另请参阅