RegistryKey 類別

定義

表示 Windows 登錄中的機碼層級節點。Represents a key-level node in the Windows registry. 這個類別的作用是登錄封裝。This class is a registry encapsulation.

public ref class RegistryKey sealed : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class RegistryKey : MarshalByRefObject, IDisposable
type RegistryKey = class
    inherit MarshalByRefObject
    interface IDisposable
Public NotInheritable Class RegistryKey
Inherits MarshalByRefObject
Implements IDisposable
繼承
屬性
實作

範例

下列程式碼範例示範如何在 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實例,請使用Registry類別的其中一個靜態成員。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. 系統會根據儲存在其中的專案邏輯順序,以階層式格式來組織登錄(請參閱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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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()

將指定的開啟登錄機碼的所有屬性 (Attribute) 寫入登錄中。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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)

使用指定的檢視,開啟本機電腦上表示要求機碼的新 RegistryKeyOpens a new RegistryKey that represents the requested key on the local machine with the specified view.

OpenRemoteBaseKey(RegistryHive, String)

開啟遠端電腦上表示要求機碼的新 RegistryKeyOpens 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.

明確介面實作

IDisposable.Dispose()

對目前的機碼執行 Close()Performs a Close() on the current key.

擴充方法

GetAccessControl(RegistryKey)
GetAccessControl(RegistryKey, AccessControlSections)
SetAccessControl(RegistryKey, RegistrySecurity)

適用於

另請參閱