RegistryKey.GetValue 方法

定义

检索与指定名称关联的值。Retrieves the value associated with the specified name.

重载

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.

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.

public:
 System::Object ^ GetValue(System::String ^ name, System::Object ^ defaultValue, Microsoft::Win32::RegistryValueOptions options);
public object GetValue (string name, object defaultValue, Microsoft.Win32.RegistryValueOptions options);
[System.Runtime.InteropServices.ComVisible(false)]
public object GetValue (string name, object defaultValue, Microsoft.Win32.RegistryValueOptions options);
member this.GetValue : string * obj * Microsoft.Win32.RegistryValueOptions -> obj
Public Function GetValue (name As String, defaultValue As Object, options As RegistryValueOptions) As Object

参数

name
String

要检索的值的名称。The name of the value to retrieve. 此字符串不区分大小写。This string is not case-sensitive.

defaultValue
Object

name 不存在时返回的值。The value to return if name does not exist.

options
RegistryValueOptions

枚举值之一,它指定对所检索值的可选处理方式。One of the enumeration values that specifies optional processing of the retrieved value.

返回

name 关联的值,按指定的 options 对其进行处理;如果未找到 defaultValue,则为 nameThe value associated with name, processed according to the specified options, or defaultValue if name is not found.

属性

异常

该用户没有读取注册表项所需的权限。The user does not have the permissions required to read from the registry key.

包含指定值的 RegistryKey 已关闭(无法访问关闭的项)。The RegistryKey that contains the specified value is closed (closed keys cannot be accessed).

包含指定值的 RegistryKey 已标记为删除。The RegistryKey that contains the specified value has been marked for deletion.

options 不是有效的 RegistryValueOptions 值;例如,无效值将强制转换为 RegistryValueOptionsoptions is not a valid RegistryValueOptions value; for example, an invalid value is cast to RegistryValueOptions.

用户没有必需的注册表权限。The user does not have the necessary registry rights.

示例

下面的代码示例创建一个测试键,添加一个具有嵌入的环境变量的值,并在展开和未展开的窗体中检索值。The following code sample creates a test key, adds a value with an embedded environment variable, and retrieves the value in both expanded and unexpanded forms.

#using <Microsoft.VisualBasic.dll>

using namespace System;
using namespace Microsoft::Win32;
using namespace Microsoft::VisualBasic;

int main()
{
    // Delete and recreate the test key.
    Registry::CurrentUser->DeleteSubKey( L"RegistryValueOptionsExample", false );
    RegistryKey ^ rk = 
        Registry::CurrentUser->CreateSubKey( L"RegistryValueOptionsExample" );
   
    // Add a value that contains an environment variable.
    rk->SetValue( L"ExpandValue", L"The path is %PATH%", 
        RegistryValueKind::ExpandString );
   
    // Retrieve the value, first without expanding the environment
    // variable and then expanding it.
    Console::WriteLine( L"Unexpanded: \"{0}\"", 
                        rk->GetValue( L"ExpandValue", 
                        L"No Value", 
                        RegistryValueOptions::DoNotExpandEnvironmentNames ) );
    Console::WriteLine( L"Expanded: \"{0}\"", rk->GetValue( L"ExpandValue" ) );
 
    return 0;
} //Main
using System;
using Microsoft.Win32;
using Microsoft.VisualBasic;

public class Example
{
    public static void Main()
    {
        // Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistryValueOptionsExample", false);
        RegistryKey rk = 
            Registry.CurrentUser.CreateSubKey("RegistryValueOptionsExample");

        // Add a value that contains an environment variable.
        rk.SetValue("ExpandValue", "The path is %PATH%", RegistryValueKind.ExpandString);

        // Retrieve the value, first without expanding the environment 
        // variable and then expanding it.
        Console.WriteLine("Unexpanded: \"{0}\"", 
            rk.GetValue("ExpandValue", "No Value", 
            RegistryValueOptions.DoNotExpandEnvironmentNames));
        Console.WriteLine("Expanded: \"{0}\"", rk.GetValue("ExpandValue"));
    } //Main
} //Example
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistryValueOptionsExample", False)
        Dim rk As RegistryKey = _
            Registry.CurrentUser.CreateSubKey("RegistryValueOptionsExample")

        ' Add a value that contains an environment variable.
        rk.SetValue("ExpandValue", "The path is %PATH%", _
            RegistryValueKind.ExpandString)

        ' Retrieve the value, first without expanding the environment 
        ' variable and then expanding it.
        Console.WriteLine("Unexpanded: ""{0}""", _
            rk.GetValue("ExpandValue", "No Value", _
            RegistryValueOptions.DoNotExpandEnvironmentNames))
        Console.WriteLine("Expanded: ""{0}""", rk.GetValue("ExpandValue"))
    End Sub
End Class

注解

使用此重载可指定对检索到的值进行特殊处理。Use this overload to specify special processing of the retrieved value. 例如,你可以指定在检索 RegistryValueKind.ExpandString 类型的注册表值时 RegistryValueOptions.DoNotExpandEnvironmentNames,以便在不展开嵌入的环境变量的情况下检索字符串。For example, you can specify RegistryValueOptions.DoNotExpandEnvironmentNames when retrieving a registry value of type RegistryValueKind.ExpandString to retrieve the string without expanding embedded environment variables.

如果 name 不存在,请使用 defaultValue 参数来指定要返回的值。Use the defaultValue parameter to specify the value to return if name does not exist.

备注

注册表项可以有一个不与任何名称关联的值。A registry key can have one value that is not associated with any name. 在注册表编辑器中显示此未命名值时,将显示字符串 "(默认值)",而不是名称。When this unnamed value is displayed in the registry editor, the string "(Default)" appears instead of a name. 若要检索此未命名值,请为 name指定 null 或空字符串("")。To retrieve this unnamed value, specify either null or the empty string ("") for name.

GetValue 不支持读取类型 REG_NONE 或 REG_LINK 的值。GetValue does not support reading values of type REG_NONE or REG_LINK. 在这两种情况下,将返回默认值(null)而不是实际值。In both cases, the default value (null) is returned instead of the actual value.

另请参阅

GetValue(String)

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

public:
 System::Object ^ GetValue(System::String ^ name);
public object GetValue (string name);
member this.GetValue : string -> obj
Public Function GetValue (name As String) As Object

参数

name
String

要检索的值的名称。The name of the value to retrieve. 此字符串不区分大小写。This string is not case-sensitive.

返回

name 关联的值;如果未找到 null,则为 nameThe value associated with name, or null if name is not found.

异常

该用户没有读取注册表项所需的权限。The user does not have the permissions required to read from the registry key.

包含指定值的 RegistryKey 已关闭(无法访问关闭的项)。The RegistryKey that contains the specified value is closed (closed keys cannot be accessed).

包含指定值的 RegistryKey 已标记为删除。The RegistryKey that contains the specified value has been marked for deletion.

用户没有必需的注册表权限。The user does not have the necessary registry rights.

示例

下面的代码示例创建一个测试键,并向该键添加不同数据类型的值。The following code example creates a test key and adds values of different data types to the key. 然后,该示例读取名称/值对,并使用 GetValueKind 方法检索相应的注册表数据类型,将其显示在控制台中。The example then reads the name/value pairs and displays them to the console, using the GetValueKind method to retrieve the corresponding registry data types.

using namespace System;
using namespace Microsoft::Win32;
int main()
{
   
   // Delete and recreate the test key.
   Registry::CurrentUser->DeleteSubKey( "RegistryValueKindExample", false );
   RegistryKey ^ rk = Registry::CurrentUser->CreateSubKey( "RegistryValueKindExample" );
   
   // Create name/value pairs.
   // This overload supports QWord (long) values. 
   rk->SetValue( "QuadWordValue", 42, RegistryValueKind::QWord );
   
   // The following SetValue calls have the same effect as using the
   // SetValue overload that does not specify RegistryValueKind.
   //
   rk->SetValue( "DWordValue", 42, RegistryValueKind::DWord );
   rk->SetValue( "MultipleStringValue", gcnew array<String^>{
      "One","Two","Three"
   }, RegistryValueKind::MultiString );
   rk->SetValue( "BinaryValue", gcnew array<Byte>{
      10,43,44,45,14,255
   }, RegistryValueKind::Binary );
   rk->SetValue( "StringValue", "The path is %PATH%", RegistryValueKind::String );
   
   // This overload supports setting expandable string values. Compare
   // the output from this value with the previous string value.
   rk->SetValue( "ExpandedStringValue", "The path is %PATH%", RegistryValueKind::ExpandString );
   
   // Display all the name/value pairs stored in the test key, with the
   // registry data type in parentheses.
   //
   array<String^>^valueNames = rk->GetValueNames();
   System::Collections::IEnumerator^ myEnum = valueNames->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum->Current);
      RegistryValueKind rvk = rk->GetValueKind( s );
      switch ( rvk )
      {
         case RegistryValueKind::MultiString:
         {
            array<String^>^values = (array<String^>^)rk->GetValue( s );
            Console::Write( "\r\n {0} ({1}) =", s, rvk );
            for ( int i = 0; i < values->Length; i++ )
            {
               if (i != 0) Console::Write(",");
               Console::Write( " \"{0}\"", values[ i ] );

            }
            Console::WriteLine();
            break;
         }
         case RegistryValueKind::Binary:
         {
            array<Byte>^bytes = (array<Byte>^)rk->GetValue( s );
            Console::Write( "\r\n {0} ({1}) =", s, rvk );
            for ( int i = 0; i < bytes->Length; i++ )
            {
               
               // Display each byte as two hexadecimal digits.
               Console::Write( " {0:X2}", bytes[ i ] );

            }
            Console::WriteLine();
            break;
         }
         default:
            Console::WriteLine( "\r\n {0} ({1}) = {2}", s, rvk, rk->GetValue( s ) );
            break;
      }
   }
}
/*

This code example produces the following output:
 QuadWordValue (QWord) = 42

 DWordValue (DWord) = 42

 MultipleStringValue (MultiString) =, "One", "Two", "Three"

 BinaryValue (Binary) = 0A 2B 2C 2D 0E FF

 StringValue (String) = The path is %PATH%

 ExpandedStringValue (ExpandString) = The path is C:\Program Files\Microsoft.NET\SDK\v2.0\Bin;
 [***The remainder of this output is omitted.***]

*/
using System;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistryValueKindExample", false);
        RegistryKey rk = Registry.CurrentUser.CreateSubKey("RegistryValueKindExample");

        // Create name/value pairs.

        // This overload supports QWord (long) values. 
        rk.SetValue("QuadWordValue", 42, RegistryValueKind.QWord);

        // The following SetValue calls have the same effect as using the
        // SetValue overload that does not specify RegistryValueKind.
        //
        rk.SetValue("DWordValue", 42, RegistryValueKind.DWord);
        rk.SetValue("MultipleStringValue", new string[] {"One", "Two", "Three"}, RegistryValueKind.MultiString);
        rk.SetValue("BinaryValue", new byte[] {10, 43, 44, 45, 14, 255}, RegistryValueKind.Binary);
        rk.SetValue("StringValue", "The path is %PATH%", RegistryValueKind.String);

        // This overload supports setting expandable string values. Compare
        // the output from this value with the previous string value.
        rk.SetValue("ExpandedStringValue", "The path is %PATH%", RegistryValueKind.ExpandString);

        // Display all name/value pairs stored in the test key, with each
        // registry data type in parentheses.
        //
        string[] valueNames = rk.GetValueNames();
        foreach (string s in valueNames)
        {
            RegistryValueKind rvk = rk.GetValueKind(s);
            switch (rvk)
            {
                case RegistryValueKind.MultiString :
                    string[] values = (string[]) rk.GetValue(s);
                    Console.Write("\r\n {0} ({1}) =", s, rvk);
                    for (int i = 0; i < values.Length; i++)
                    {
                        if (i != 0) Console.Write(",");
                        Console.Write(" \"{0}\"", values[i]);
                    }
                    Console.WriteLine();
                    break;
                
                case RegistryValueKind.Binary :
                    byte[] bytes = (byte[]) rk.GetValue(s);
                    Console.Write("\r\n {0} ({1}) =", s, rvk);
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        // Display each byte as two hexadecimal digits.
                        Console.Write(" {0:X2}", bytes[i]);
                    }
                    Console.WriteLine();
                    break;
                
                default :
                    Console.WriteLine("\r\n {0} ({1}) = {2}", s, rvk, rk.GetValue(s));
                    break;
            }
        }
    }
}
/*

This code example produces the following output:
 QuadWordValue (QWord) = 42

 DWordValue (DWord) = 42

 MultipleStringValue (MultiString) =, "One", "Two", "Three"

 BinaryValue (Binary) = 0A 2B 2C 2D 0E FF

 StringValue (String) = The path is %PATH%

 ExpandedStringValue (ExpandString) = The path is C:\Program Files\Microsoft.NET\SDK\v2.0\Bin;
 [***The remainder of this output is omitted.***]

*/
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistryValueKindExample", False)
        Dim rk As RegistryKey = Registry.CurrentUser.CreateSubKey("RegistryValueKindExample")
        
        ' Create name/value pairs.
        ' This overload supports QWord (long) values. 
        rk.SetValue("QuadWordValue", 42, RegistryValueKind.QWord)
        
        ' The following SetValue calls have the same effect as using the
        ' SetValue overload that does not specify RegistryValueKind.
        '
        rk.SetValue("DWordValue", 42, RegistryValueKind.DWord)
        rk.SetValue("MultipleStringValue", New String() {"One", "Two", "Three"}, RegistryValueKind.MultiString)
        rk.SetValue("BinaryValue", New Byte() {10, 43, 44, 45, 14, 255}, RegistryValueKind.Binary)
        rk.SetValue("StringValue", "The path is %PATH%", RegistryValueKind.String) 
        
        ' This overload supports setting expandable string values. Compare
        ' the output from this value with the previous string value.
        rk.SetValue("ExpandedStringValue", "The path is %PATH%", RegistryValueKind.ExpandString)
        
        
        ' Display all name/value pairs stored in the test key, with each
        ' registry data type in parentheses.
        '
        Dim valueNames As String() = rk.GetValueNames()
        Dim s As String
        For Each s In  valueNames
            Dim rvk As RegistryValueKind = rk.GetValueKind(s)
            Select Case rvk
                Case RegistryValueKind.MultiString
                    Dim values As String() = CType(rk.GetValue(s), String())
                    Console.Write(vbCrLf & " {0} ({1}) =", s, rvk)
                    For i As Integer = 0 To values.Length - 1
                        If i <> 0 Then Console.Write(",")
                        Console.Write(" ""{0}""", values(i))
                    Next i
                    Console.WriteLine()
                
                Case RegistryValueKind.Binary
                    Dim bytes As Byte() = CType(rk.GetValue(s), Byte())
                    Console.Write(vbCrLf & " {0} ({1}) =", s, rvk)
                    For i As Integer = 0 To bytes.Length - 1
                        ' Display each byte as two hexadecimal digits.
                        Console.Write(" {0:X2}", bytes(i))
                    Next i
                    Console.WriteLine()
                
                Case Else
                    Console.WriteLine(vbCrLf & " {0} ({1}) = {2}", s, rvk, rk.GetValue(s))
            End Select
        Next s
    End Sub
End Class

'
'This code example produces the following output (some output is omitted):
'
' QuadWordValue (QWord) = 42
'
' DWordValue (DWord) = 42
'
' MultipleStringValue (MultiString) = "One", "Two", "Three"
'
' BinaryValue (Binary) = 0A 2B 2C 2D 0E FF
'
' StringValue (String) = The path is %PATH%
'
' ExpandedStringValue (ExpandString) = The path is C:\Program Files\Microsoft.NET\SDK\v2.0\Bin;
' [***The remainder of this output is omitted.***]

注解

备注

注册表项可以有一个不与任何名称关联的值。A registry key can have one value that is not associated with any name. 在注册表编辑器中显示此未命名值时,将显示字符串 "(默认值)",而不是名称。When this unnamed value is displayed in the registry editor, the string "(Default)" appears instead of a name. 若要检索此未命名值,请为 name指定 null 或空字符串("")。To retrieve this unnamed value, specify either null or the empty string ("") for name.

GetValue 方法检索可扩充字符串值(RegistryValueKind.ExpandString)时,它将使用本地环境中的数据展开环境字符串。When the GetValue method retrieves expandable string values (RegistryValueKind.ExpandString), it expands environment strings using data from the local environment. 若要从远程计算机上的注册表中检索可扩充字符串值,请使用 GetValue(String, Object, RegistryValueOptions) 方法重载来指定不需要扩展环境字符串。To retrieve expandable string values from the registry on a remote computer, use the GetValue(String, Object, RegistryValueOptions) method overload to specify that you do not want environment strings expanded.

备注

如果包含对环境变量的可扩充引用的值存储为字符串(RegistryValueKind.String),而不是作为可扩充字符串(RegistryValueKind.ExpandString)存储,则 GetValue 不会将其展开。If a value containing expandable references to environment variables has been stored as a string (RegistryValueKind.String), rather than as an expandable string (RegistryValueKind.ExpandString), GetValue does not expand it. 可以通过调用 ExpandEnvironmentVariables 方法来扩展此类字符串。You can expand such a string after it has been retrieved by calling the ExpandEnvironmentVariables method.

备注

PerformanceData 键检索数据的建议方法是使用 PerformanceCounter 类,而不是 RegistryKey.GetValue 方法。The recommended way to retrieve data from the PerformanceData key is to use the PerformanceCounter class rather than the RegistryKey.GetValue method.

GetValue 不支持读取类型 REG_NONE 或 REG_LINK 的值。GetValue does not support reading values of type REG_NONE or REG_LINK. 在这两种情况下,将返回默认值(null)而不是实际值。In both cases, the default value (null) is returned instead of the actual value.

另请参阅

GetValue(String, Object)

检索与指定名称关联的值。Retrieves the value associated with the specified name. 如果未找到名称,则返回你提供的默认值。If the name is not found, returns the default value that you provide.

public:
 System::Object ^ GetValue(System::String ^ name, System::Object ^ defaultValue);
public object GetValue (string name, object defaultValue);
member this.GetValue : string * obj -> obj
Public Function GetValue (name As String, defaultValue As Object) As Object

参数

name
String

要检索的值的名称。The name of the value to retrieve. 此字符串不区分大小写。This string is not case-sensitive.

defaultValue
Object

name 不存在时返回的值。The value to return if name does not exist.

返回

name 关联的值,不展开嵌入的任何环境变量;如果未找到 defaultValue,则为 nameThe value associated with name, with any embedded environment variables left unexpanded, or defaultValue if name is not found.

异常

该用户没有读取注册表项所需的权限。The user does not have the permissions required to read from the registry key.

包含指定值的 RegistryKey 已关闭(无法访问关闭的项)。The RegistryKey that contains the specified value is closed (closed keys cannot be accessed).

包含指定值的 RegistryKey 已标记为删除。The RegistryKey that contains the specified value has been marked for deletion.

用户没有必需的注册表权限。The user does not have the necessary registry rights.

示例

下面的代码示例创建一个具有值的测试键并检索该值。The following code example creates a test key with a value and retrieves that value. 然后,该示例尝试从该键检索不存在的值;在这种情况下,GetValue 方法返回指定的默认值。The example then attempts to retrieve a nonexistent value from the key; in this case the GetValue method returns the specified default value.

using namespace System;
using namespace Microsoft::Win32;

public ref class RegGetDef
{
public:
    static void Main()
    {
        // Create a reference to a valid key.  In order for this code to
        // work, the indicated key must have been created previously.
        // The key name is not case-sensitive.
        RegistryKey^ rk = Registry::LocalMachine->OpenSubKey("Software\\myTestKey", false);
        // Get the value from the specified name/value pair in the key.
        String^ valueName = "myTestValue";

        Console::WriteLine("Retrieving registry value ...");
        Console::WriteLine();
        Object^ o = rk->GetValue(valueName);
        Console::WriteLine("Object Type = " + o->GetType()->FullName);
        Console::WriteLine();
        switch (rk->GetValueKind(valueName))
        {
            case RegistryValueKind::String:
            case RegistryValueKind::ExpandString:
                Console::WriteLine("Value = " + o);
                break;
            case RegistryValueKind::Binary:
                for each (Byte^ b in (array<Byte^>^)o)
                {
                    Console::Write("{0:x2} ", b);
                }
                Console::WriteLine();
                break;
            case RegistryValueKind::DWord:
                Console::WriteLine("Value = " + Convert::ToString((Int32^)o));
                break;
            case RegistryValueKind::QWord:
                Console::WriteLine("Value = " + Convert::ToString((Int64^)o));
                break;
            case RegistryValueKind::MultiString:
                for each (String^ s in (array<String^>^)o)
                {
                    Console::Write("[{0:s}], ", s);
                }
                Console::WriteLine();
                break;
            default:
                Console::WriteLine("Value = (Unknown)");
                break;
        }

        // Attempt to retrieve a value that does not exist; the specified
        // default value is returned.
        String^ def = (String^)rk->GetValue("notavalue", "The default to return");
        Console::WriteLine();
        Console::WriteLine(def);
        
        rk->Close();
    }
};

int main()
{
    RegGetDef::Main();
}
/*
Output:
Retrieving registry value ...

Object Type = System.String

Value = testData

The default to return
*/
using System;
using Microsoft.Win32;

class RegGetDef
{
    public static void Main()
    {
        // Create a reference to a valid key.  In order for this code to
        // work, the indicated key must have been created previously.
        // The key name is not case-sensitive.
        RegistryKey rk = Registry.LocalMachine.OpenSubKey("Software\\myTestKey", false);
        // Get the value from the specified name/value pair in the key.

        string valueName = "myTestValue";

        Console.WriteLine("Retrieving registry value ...");
        Console.WriteLine();
        object o = rk.GetValue(valueName);
        Console.WriteLine("Object Type = " + o.GetType().FullName);
        Console.WriteLine();
        switch (rk.GetValueKind(valueName))
        {
            case RegistryValueKind.String:
            case RegistryValueKind.ExpandString:
                Console.WriteLine("Value = " + o);
                break;
            case RegistryValueKind.Binary:
                foreach (byte b in (byte[])o)
                {
                    Console.Write("{0:x2} ", b);
                }
                Console.WriteLine();
                break;
            case RegistryValueKind.DWord:
                Console.WriteLine("Value = " + Convert.ToString((Int32)o));
                break;
            case RegistryValueKind.QWord:
                Console.WriteLine("Value = " + Convert.ToString((Int64)o));
                break;
            case RegistryValueKind.MultiString:
                foreach (string s in (string[])o)
                {
                    Console.Write("[{0:s}], ", s);
                }
                Console.WriteLine();
                break;
            default:
                Console.WriteLine("Value = (Unknown)");
                break;
        }

        // Attempt to retrieve a value that does not exist; the specified
        // default value is returned.
        string def = (string)rk.GetValue("notavalue", "The default to return");
        Console.WriteLine();
        Console.WriteLine(def);
        
        rk.Close();
    }
}
/*
Output:
Retrieving registry value ...

Object Type = System.String

Value = testData

The default to return
*/
Imports Microsoft.Win32

Public Class RegGetDef
    Public Shared Sub Main()
        ' Create a reference to a valid key.  In order for this code to
        ' work, the indicated key must have been created previously.
        ' The key name is not case-sensitive.
        Dim rk As RegistryKey = Registry.LocalMachine.OpenSubKey("Software\myTestKey", false)

        ' Get the value from the specified name/value pair in the key.
        Dim valueName As String = "myTestValue"

        Console.WriteLine("Retrieving registry value ...")
        Console.WriteLine()
        Dim o As Object = rk.GetValue(valueName)
        Console.WriteLine("Object Type = " + o.GetType().FullName)
        Console.WriteLine()
        Select Case rk.GetValueKind(valueName)
            Case RegistryValueKind.String
            Case RegistryValueKind.ExpandString
                Console.WriteLine("Value = " + o)
            Case RegistryValueKind.Binary
                For Each b As Byte In CType(o,Byte())
                    Console.Write("{0:x2} ", b)
                Next b
                Console.WriteLine()
            Case RegistryValueKind.DWord
                Console.WriteLine("Value = " + Convert.ToString(CType(o,Int32)))
            Case RegistryValueKind.QWord
                Console.WriteLine("Value = " + Convert.ToString(CType(o,Int64)))
            Case RegistryValueKind.MultiString
                For Each s As String In CType(o,String())
                    Console.Write("[{0:s}], ", s)
                Next s
                Console.WriteLine()
            Case Else
                Console.WriteLine("Value = (Unknown)")
        End Select

        ' Attempt to retrieve a value that does not exist; the specified
        ' default value is returned.
        Dim Def As String = rk.GetValue("notavalue", "The default to return")
        Console.WriteLine()
        Console.WriteLine(def)
        
        rk.Close()
    End Sub
End Class
'
' Output:
' Retrieving registry value ...
'
' Object Type = System.String
'
' Value = testData
'
'The default to return

注解

使用 GetValue 的此重载来处理名称尚不存在的情况,例如,首次运行应用程序时。Use this overload of GetValue to handle the case where a name does not exist yet - for example, the first time your application is run. 无论何时调用此重载,都可以使用 defaultValue 参数指定在 name 不存在时要返回的值。Whenever you call this overload, use the defaultValue parameter to specify the value to return if name does not exist.

备注

注册表项可以有一个不与任何名称关联的值。A registry key can have one value that is not associated with any name. 在注册表编辑器中显示此未命名值时,将显示字符串 "(默认值)",而不是名称。When this unnamed value is displayed in the registry editor, the string "(Default)" appears instead of a name. 若要检索此未命名值,请为 name指定 null 或空字符串("")。To retrieve this unnamed value, specify either null or the empty string ("") for name.

GetValue 方法检索可扩充字符串值(RegistryValueKind.ExpandString)时,它将使用本地环境中的数据展开环境字符串。When the GetValue method retrieves expandable string values (RegistryValueKind.ExpandString), it expands environment strings using data from the local environment. 若要从远程计算机上的注册表中检索可扩充字符串值,请使用 GetValue 重载来指定不需要扩展环境字符串。To retrieve expandable string values from the registry on a remote computer, use the GetValue overload to specify that you do not want environment strings expanded.

备注

如果包含对环境变量的可扩充引用的值存储为字符串(RegistryValueKind.String),而不是作为可扩充字符串(RegistryValueKind.ExpandString)存储,则 GetValue 方法不会将其展开。If a value containing expandable references to environment variables has been stored as a string (RegistryValueKind.String), rather than as an expandable string (RegistryValueKind.ExpandString), the GetValue method does not expand it. 可以通过调用 ExpandEnvironmentVariables 方法来扩展此类字符串。You can expand such a string after it has been retrieved by calling the ExpandEnvironmentVariables method.

备注

PerformanceData 键检索数据的建议方法是使用 PerformanceCounter 类,而不是 RegistryKey.GetValue 方法。The recommended way to retrieve data from the PerformanceData key is to use the PerformanceCounter class rather than the RegistryKey.GetValue method.

GetValue 不支持读取类型 REG_NONE 或 REG_LINK 的值。GetValue does not support reading values of type REG_NONE or REG_LINK. 在这两种情况下,将返回默认值(null)而不是实际值。In both cases, the default value (null) is returned instead of the actual value.

另请参阅

适用于