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. 该示例演示了在名称/值对不存在时,存储和检索默认(无名称)名称/值对,并使用 defaultValueThe 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.

Registry 类公开的 base 或 root RegistryKey 实例描绘了注册表中子项和值的基本存储机制。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.

适用于

另请参阅