Registry Klasse

Definition

Stellt RegistryKey-Objekte, die die Stammschlüssel in der Windows-Registrierung darstellen, sowie static-Methoden für den Zugriff auf Schlüssel-/-Wert-Paare bereit.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
public ref class Registry sealed
public static class Registry
public sealed class Registry
[System.Runtime.InteropServices.ComVisible(true)]
public static class Registry
type Registry = class
Public Class Registry
Public NotInheritable Class Registry
Vererbung
Registry
Attribute

Beispiele

Dieser Abschnitt enthält zwei Codebeispiele.This section contains two code examples. Das erste Beispiel veranschaulicht Stamm Schlüssel, und im zweiten Beispiel werden die Methoden staticGetValue und SetValue veranschaulicht.The first example demonstrates root keys, and the second example demonstrates the staticGetValue and SetValue methods.

Beispiel 1Example 1

Im folgenden Codebeispiel wird veranschaulicht, wie die Unterschlüssel des HKEY_USERS Schlüssels abgerufen und die Namen auf dem Bildschirm gedruckt werden.The following code example demonstrates how to retrieve the subkeys of the HKEY_USERS key, and print their names to the screen. Verwenden Sie die OpenSubKey-Methode, um eine Instanz des jeweiligen unter Schlüssels zu erstellen.Use the OpenSubKey method to create an instance of the particular subkey of interest. Sie können dann andere Vorgänge in RegistryKey verwenden, um diesen Schlüssel zu bearbeiten.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

Beispiel 2Example 2

Im folgenden Codebeispiel werden die Werte mehrerer Datentypen in einem Beispiel Schlüssel gespeichert, und der Schlüssel wird wie folgt erstellt. Anschließend werden die Werte abgerufen und angezeigt.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. Das Beispiel veranschaulicht das Speichern und Abrufen des Standard Paars (Name/Wert-Paar) und die Verwendung von defaultValue, wenn kein Name/Wert-Paar vorhanden ist.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.

Hinweise

Diese Klasse stellt den Satz von Standard Stamm Schlüsseln in der Registrierung auf Computern bereit, auf denen Windows ausgeführt wird.This class provides the set of standard root keys found in the registry on machines running Windows. Die Registrierung ist eine Speicher Einrichtung für Informationen zu Anwendungen, Benutzern und Standard Systemeinstellungen.The registry is a storage facility for information about applications, users, and default system settings. Beispielsweise können Anwendungen die Registrierung zum Speichern von Informationen verwenden, die nach dem Schließen der Anwendung beibehalten werden müssen, und auf die gleichen Informationen zugreifen, wenn die Anwendung erneut geladen wird.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. Beispielsweise können Sie Farbeinstellungen, Bildschirm Positionen oder die Größe des Fensters speichern.For instance, you can store color preferences, screen locations, or the size of the window. Sie können diese Daten für jeden Benutzer steuern, indem Sie die Informationen an einem anderen Speicherort in der Registrierung speichern.You can control this data for each user by storing the information in a different location in the registry.

Die Basis-oder Stamm RegistryKey Instanzen, die von der Registry-Klasse verfügbar gemacht werden, beschreiben den grundlegenden Speichermechanismus für Unterschlüssel und Werte in der Registrierung.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. Alle Schlüssel sind schreibgeschützt, da die Registrierung von Ihrem vorhanden sein abhängig ist.All keys are read-only because the registry depends on their existence. Die von Registry verfügbar gemachten Schlüssel lauten wie folgt:The keys exposed by Registry are:

CurrentUser
Speichert Informationen zu Benutzereinstellungen.Stores information about user preferences.

LocalMachine
Speichert Konfigurationsinformationen für den lokalen Computer.Stores configuration information for the local machine.

ClassesRoot
Speichert Informationen zu Typen (und Klassen) und deren Eigenschaften.Stores information about types (and classes) and their properties.

Users
Speichert Informationen zur Standardbenutzer Konfiguration.Stores information about the default user configuration.

PerformanceData
Speichert Leistungsinformationen für Softwarekomponenten.Stores performance information for software components.

CurrentConfig
Speichert Nichtbenutzer spezifische Hardwareinformationen.Stores non-user-specific hardware information.

DynData
Speichert dynamische Daten.Stores dynamic data.

Nachdem Sie den Stamm Schlüssel identifiziert haben, unter dem Sie Informationen aus der Registrierung speichern/abrufen möchten, können Sie die RegistryKey-Klasse verwenden, um Unterschlüssel hinzuzufügen oder zu entfernen und die Werte für einen bestimmten Schlüssel zu bearbeiten.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 Geräte können mithilfe der Plug & Play-Schnittstelle automatisch Informationen in der Registrierung platzieren.Hardware devices can place information in the registry automatically using the Plug and Play interface. Software für die Installation von Gerätetreibern kann Informationen in der Registrierung durch Schreiben in Standard-APIs platzieren.Software for installing device drivers can place information in the registry by writing to standard APIs.

Statische Methoden zum erhalten und Festlegen von WertenStatic Methods for Getting and Setting Values

In der .NET Framework Version 2,0 enthält die Registry-Klasse auch staticGetValue und SetValue Methoden zum Festlegen und Abrufen von Werten aus Registrierungs Schlüsseln.In the .NET Framework version 2.0, the Registry class also contains staticGetValue and SetValue methods for setting and retrieving values from registry keys. Diese Methoden öffnen und schließen Registrierungsschlüssel jedes Mal, wenn Sie verwendet werden, sodass Sie nicht ebenso wie analoge Methoden in der RegistryKey-Klasse sind, wenn Sie auf eine große Anzahl von Werten zugreifen.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.

Die RegistryKey-Klasse stellt auch Methoden bereit, die es Ihnen ermöglichen, die Windows-Zugriffs Steuerungs Sicherheit für Registrierungsschlüssel festzulegen, den Datentyp eines Werts vor dem Abrufen zu testen und Schlüssel zu löschen.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.

Felder

ClassesRoot

Definiert die Typen (oder Klassen) von Dokumenten und die diesen Typen zugeordneten Eigenschaften.Defines the types (or classes) of documents and the properties associated with those types. Dieses Feld liest den Basisschlüssel HKEY_CLASSES_ROOT der Windows-Registrierung.This field reads the Windows registry base key HKEY_CLASSES_ROOT.

CurrentConfig

Enthält benutzerunabhängige Konfigurationsinformationen über die Hardware.Contains configuration information pertaining to the hardware that is not specific to the user. Dieses Feld liest den Basisschlüssel HKEY_CURRENT_CONFIG der Windows-Registrierung.This field reads the Windows registry base key HKEY_CURRENT_CONFIG.

CurrentUser

Enthält Informationen über die Einstellungen des aktuellen Benutzers.Contains information about the current user preferences. Dieses Feld liest den Basisschlüssel HKEY_CURRENT_USER der Windows-Registrierung.This field reads the Windows registry base key HKEY_CURRENT_USER.

DynData

Speichert dynamische Registrierungsdaten.Contains dynamic registry data. Dieses Feld liest den Basisschlüssel HKEY_DYN_DATA der Windows-Registrierung.This field reads the Windows registry base key HKEY_DYN_DATA.

LocalMachine

Speichert die Konfigurationsinformationen für den lokalen Computer.Contains the configuration data for the local machine. Dieses Feld liest den Basisschlüssel HKEY_LOCAL_MACHINE der Windows-Registrierung.This field reads the Windows registry base key HKEY_LOCAL_MACHINE.

PerformanceData

Enthält Informationen zur Leistung für Softwarekomponenten.Contains performance information for software components. Dieses Feld liest den Basisschlüssel HKEY_PERFORMANCE_DATA der Windows-Registrierung.This field reads the Windows registry base key HKEY_PERFORMANCE_DATA.

Users

Enthält Informationen über die Standardkonfiguration des Benutzer.Contains information about the default user configuration. Dieses Feld liest den Basisschlüssel HKEY_USERS der Windows-Registrierung.This field reads the Windows registry base key HKEY_USERS.

Methoden

GetValue(String, String, Object)

Ruft den Wert ab, der dem angegebenen Namen im angegebenen Registrierungsschlüssel zugeordnet ist.Retrieves the value associated with the specified name, in the specified registry key. Wenn der Name im angegebenen Schlüssel nicht gefunden wird, wird ein von Ihnen bereitgestellter Standardwert zurückgegeben, oder null, wenn der angegebene Schlüssel nicht vorhanden ist.If 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)

Legt das angegebene Name-/Wert-Paar für den angegebenen Registrierungsschlüssel fest.Sets the specified name/value pair on the specified registry key. Wenn der angegebene Schlüssel nicht vorhanden ist, wird er erstellt.If the specified key does not exist, it is created.

SetValue(String, String, Object, RegistryValueKind)

Legt unter Verwendung des angegebenen Registrierungsdatentyps das Name-/Wert-Paar für den angegebenen Registrierungsschlüssel fest.Sets the name/value pair on the specified registry key, using the specified registry data type. Wenn der angegebene Schlüssel nicht vorhanden ist, wird er erstellt.If the specified key does not exist, it is created.

Gilt für:

Siehe auch