語言

RegistryKey.SetValue 方法

定義

設定登錄表鍵中名稱/值對的值。 根據過載情況,登錄檔資料類型可根據所儲存的資料類型或指定的 RegistryValueKind資料類型決定。

多載

名稱 Description
SetValue(String, Object)

設定指定的名稱/值對。

SetValue(String, Object, RegistryValueKind)

在登錄檔鍵中設定名稱/值對的值,使用指定的登錄檔資料型態。

SetValue(String, Object)

來源:
RegistryKey.cs

設定指定的名稱/值對。

public:
 void SetValue(System::String ^ name, System::Object ^ value);
public void SetValue(string? name, object value);
public void SetValue(string name, object value);
member this.SetValue : string * obj -> unit
Public Sub SetValue (name As String, value As Object)

參數

name
String

要儲存的價值名稱。

value
Object

要儲存的資料。

例外狀況

value 是 null。

value 是不支援的資料型態。

包含指定值的 RegistryKey 是封閉的(閉金鑰無法存取)。

該 RegistryKey 金鑰為唯讀,無法寫入;例如,該金鑰尚未以寫入權限開啟。

-或-

RegistryKey 物件代表根節點,作業系統則Windows千禧版或 Windows 98。

使用者沒有建立或修改登錄表金鑰所需的權限。

RegistryKey 物件代表根節點,作業系統Windows 2000、Windows XP 或 Windows Server 2003。

範例

以下程式碼範例展示了該方法在設定值時如何 SetValue 決定登錄資料型態。 範例中建立一個測試鍵,並將不同資料型態的值加入鍵中。 接著範例讀取名稱/值對,並以此方式顯示給主控台,並用該 GetValueKind 方法顯示對應的登錄檔資料型別。

using namespace System;
using namespace Microsoft::Win32;
int main()
{
   
   // Delete and recreate the test key.
   Registry::CurrentUser->DeleteSubKey( "RegistrySetValueExample", false );
   RegistryKey ^ rk = Registry::CurrentUser->CreateSubKey( "RegistrySetValueExample" );
   
   // Create name/value pairs.
   // Numeric values that cannot be interpreted as DWord (int) values
   // are stored as strings.
   rk->SetValue( "LargeNumberValue1", (long)42 );
   rk->SetValue( "LargeNumberValue2", 42000000000 );
   rk->SetValue( "DWordValue", 42 );
   array<String^>^temp0 = {"One","Two","Three"};
   rk->SetValue( "MultipleStringValue", temp0 );
   array<Byte>^temp1 = {10,43,44,45,14,255};
   rk->SetValue( "BinaryValue", temp1 );
   
   // This overload of SetValue does not support expanding strings. Use
   // the overload that allows you to specify RegistryValueKind.
   rk->SetValue( "StringValue", "The path is %PATH%" );
   
   // 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}) = \"{2}\"", s, rvk, values[ 0 ] );
            for ( int i = 1; i < values->Length; i++ )
            {
               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}) = {2:X2}", s, rvk, bytes[ 0 ] );
            for ( int i = 1; 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;
      }
   }
}
using System;
using Microsoft.Win32;

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

        // Create name/value pairs.

        // Numeric values that cannot be interpreted as DWord (int) values
        // are stored as strings.
        rk.SetValue("LargeNumberValue1", (long) 42);
        rk.SetValue("LargeNumberValue2", 42000000000);

        rk.SetValue("DWordValue", 42);
        rk.SetValue("MultipleStringValue", new string[] {"One", "Two", "Three"});
        rk.SetValue("BinaryValue", new byte[] {10, 43, 44, 45, 14, 255});

        // This overload of SetValue does not support expanding strings. Use
        // the overload that allows you to specify RegistryValueKind.
        rk.SetValue("StringValue", "The path is %PATH%");

        // 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}) = \"{2}\"", s, rvk, values[0]);
                    for (int i = 1; i < values.Length; i++)
                    {
                        Console.Write(", \"{0}\"", values[i]);
                    }
                    Console.WriteLine();
                    break;

                case RegistryValueKind.Binary :
                    byte[] bytes = (byte[]) rk.GetValue(s);
                    Console.Write("\r\n {0} ({1}) = {2:X2}", s, rvk, bytes[0]);
                    for (int i = 1; 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;
            }
        }
    }
}
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' Delete and recreate the test key.
        Registry.CurrentUser.DeleteSubKey("RegistrySetValueExample", False)
        Dim rk As RegistryKey = Registry.CurrentUser.CreateSubKey("RegistrySetValueExample")
        
        ' Create name/value pairs.
        ' Numeric values that cannot be interpreted as DWord (int) values
        ' are stored as strings.
        rk.SetValue("LargeNumberValue1", CType(42, Long))
        rk.SetValue("LargeNumberValue2", 42000000000)
        
        rk.SetValue("DWordValue", 42)
        rk.SetValue("MultipleStringValue", New String() {"One", "Two", "Three"})
        rk.SetValue("BinaryValue", New Byte() {10, 43, 44, 45, 14, 255})
        
        ' This overload of SetValue does not support expanding strings. Use
        ' the overload that allows you to specify RegistryValueKind.
        rk.SetValue("StringValue", "The path is %PATH%")
        
        ' 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}) = ""{2}""", s, rvk, values(0))
                    Dim i As Integer
                    For i = 1 To values.Length - 1
                        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}) = {2:X2}", s, rvk, bytes(0))
                    Dim i As Integer
                    For i = 1 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

備註

由於每個登錄鍵可儲存多個值,您必須使用 name 參數指定您想設定的特定值。

Note

登錄檔鍵可以有一個不與任何名稱相關聯的值。 當這個未命名的值在登錄檔編輯器中顯示時,字串「(Default)」會取代名稱。 要設定這個未命名的值,請指定空字串(“”)null其中之一name。

要設定鍵值,必須開啟該鍵的寫入權限。 當你打開一個有寫入權限的金鑰後,你可以更改該金鑰中的任何名稱/值對。

若指定 name 值不存在於鍵中,則建立該鍵並將相關值設為 value。

這種超載 SetValue 將 64 位元整數儲存為字串(RegistryValueKind.String)。 要將 64 位元數值儲存為RegistryValueKind.QWord值,請使用指定 SetValue(String, Object, RegistryValueKind)的超載。RegistryValueKind

這種過載 SetValue 會將所有字串值儲存為 RegistryValueKind.String,即使它們包含可展開的環境變數參考。 若要將字串值儲存為可展開字串(RegistryValueKind.ExpandString),請SetValue(String, Object, RegistryValueKind)使用指定 的超載。RegistryValueKind

此方法過載會將非 32 位元整數的數值類型儲存為字串。 列舉元素以包含元素名稱的字串形式儲存。

注意事項

不要以惡意程式可能產生數千個無意義子鍵或鍵值對的方式暴露 RegistryKey 物件。 例如,不允許呼叫者輸入任意的鍵或值。

另請參閱

適用於

SetValue(String, Object, RegistryValueKind)

來源:
RegistryKey.cs

在登錄檔鍵中設定名稱/值對的值,使用指定的登錄檔資料型態。

public:
 void SetValue(System::String ^ name, System::Object ^ value, Microsoft::Win32::RegistryValueKind valueKind);
public void SetValue(string? name, object value, Microsoft.Win32.RegistryValueKind valueKind);
public void SetValue(string name, object value, Microsoft.Win32.RegistryValueKind valueKind);
[System.Runtime.InteropServices.ComVisible(false)]
public void SetValue(string name, object value, Microsoft.Win32.RegistryValueKind valueKind);
member this.SetValue : string * obj * Microsoft.Win32.RegistryValueKind -> unit
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.SetValue : string * obj * Microsoft.Win32.RegistryValueKind -> unit
Public Sub SetValue (name As String, value As Object, valueKind As RegistryValueKind)

參數

name
String

要儲存的價值名稱。

value
Object

要儲存的資料。

valueKind
RegistryValueKind

儲存資料時應使用的登錄資料類型。

屬性

例外狀況

value 是 null。

的 value 類型與登錄檔資料類型不符, valueKind因此資料無法正確轉換。

包含指定值的 RegistryKey 是封閉的(閉金鑰無法存取)。

該 RegistryKey 金鑰為唯讀,無法寫入;例如,該金鑰尚未以寫入權限開啟。

-或-

RegistryKey 物件代表根節點,作業系統則Windows千禧版或 Windows 98。

使用者沒有建立或修改登錄表金鑰所需的權限。

RegistryKey 物件代表根節點,作業系統Windows 2000、Windows XP 或 Windows Server 2003。

範例

以下程式碼範例建立一個測試鍵,並使用此 SetValue 方法儲存多個值,並為每個值指定登錄資料型別。 接著範例讀取名稱/值對,並以此方式顯示給主控台,並用該 GetValueKind 方法顯示對應的登錄檔資料型別。

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.***]

備註

由於每個登錄鍵可儲存多個值,您必須使用 name 參數指定您想設定的特定值。

Note

登錄檔鍵可以有一個不與任何名稱相關聯的值。 當這個未命名的值在登錄檔編輯器中顯示時,字串「(Default)」會取代名稱。 要設定這個未命名的值,請指定空字串(“”)null其中之一name。

要設定鍵值,必須開啟該鍵的寫入權限。 當你打開一個有寫入權限的金鑰後,你可以更改該金鑰中的任何名稱/值對。

若指定 name 元素不存在於鍵中,則建立該鍵,並將相應值設為 value。

Note

指定登錄檔資料型Unknown態等同於使用超載。SetValue

若指定的 value 類型與指定 valueKind不符且資料無法轉換, ArgumentException 則拋出。 例如,你可以將 a System.Int64 儲存為 RegistryValueKind.DWord,但前提是其值小於 的最大值 System.Int32。 你無法將單一字串值儲存為 RegistryValueKind.MultiString。

Note

若將盒裝值傳遞為或RegistryValueKind.DWordRegistryValueKind.QWord,則使用不變培養法進行轉換。

注意事項

不要以惡意程式可能產生數千個無意義子鍵或鍵值對的方式暴露 RegistryKey 物件。 例如,不允許呼叫者輸入任意的鍵或值。

另請參閱

適用於