Share via


RegistryKey.SetValue Metode

Definisi

Mengatur nilai pasangan nama/nilai dalam kunci registri. Bergantung pada kelebihan beban, jenis data registri ditentukan dari jenis data yang disimpan atau dari yang ditentukan RegistryValueKind.

Overload

SetValue(String, Object)

Mengatur pasangan nama/nilai yang ditentukan.

SetValue(String, Object, RegistryValueKind)

Mengatur nilai pasangan nama/nilai dalam kunci registri, menggunakan jenis data registri yang ditentukan.

SetValue(String, Object)

Sumber:
RegistryKey.cs

Mengatur pasangan nama/nilai yang ditentukan.

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)

Parameter

name
String

Nama nilai yang akan disimpan.

value
Object

Data yang akan disimpan.

Pengecualian

valueadalah null.

value adalah tipe data yang tidak didukung.

RegistryKey yang berisi nilai yang ditentukan ditutup (kunci tertutup tidak dapat diakses).

RegistryKey bersifat baca-saja, dan tidak dapat ditulis; misalnya, kunci belum dibuka dengan akses tulis.

Pengguna tidak memiliki izin yang diperlukan untuk membuat atau mengubah kunci registri.

Objek RegistryKey mewakili simpul tingkat akar, dan sistem operasinya adalah Windows 2000, Windows XP, atau Windows Server 2003.

Contoh

Contoh kode berikut menunjukkan bagaimana SetValue metode menentukan jenis data registri saat menetapkan nilai. Contohnya membuat kunci pengujian dan menambahkan nilai dari berbagai jenis data ke kunci. Contoh kemudian membaca pasangan nama/nilai dan menampilkannya ke konsol, menggunakan GetValueKind metode untuk menampilkan jenis data registri yang sesuai.

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

Keterangan

Karena banyak nilai yang dapat disimpan di setiap kunci dalam registri, Anda harus menggunakan name parameter untuk menentukan nilai tertentu yang ingin Anda tetapkan.

Catatan

Kunci registri dapat memiliki satu nilai yang tidak terkait dengan nama apa pun. Ketika nilai yang tidak disebutkan namanya ini ditampilkan di editor registri, string "(Default)" muncul alih-alih nama. Untuk mengatur nilai yang tidak disebutkan namanya ini, tentukan salah satu null atau string kosong ("") untuk name.

Untuk mengatur nilai dalam kunci, Anda harus membuka kunci dengan akses tulis. Setelah membuka kunci dengan akses tulis, Anda dapat mengubah salah satu pasangan nama/nilai dalam kunci tersebut.

Jika yang ditentukan name tidak ada di kunci, kunci dibuat dan nilai terkait diatur ke value.

Kelebihan beban ini menyimpan bilangan SetValue bulat 64-bit sebagai string (RegistryValueKind.String). Untuk menyimpan angka 64-bit sebagai RegistryValueKind.QWord nilai, gunakan SetValue(String, Object, RegistryValueKind) kelebihan beban yang menentukan RegistryValueKind.

Kelebihan beban SetValue ini menyimpan semua nilai string sebagai RegistryValueKind.String, bahkan jika berisi referensi yang dapat diperluas ke variabel lingkungan. Untuk menyimpan nilai string sebagai string yang dapat diperluas (RegistryValueKind.ExpandString), gunakan SetValue(String, Object, RegistryValueKind) kelebihan beban yang menentukan RegistryValueKind.

Jenis numerik selain bilangan bulat 32-bit disimpan sebagai string dengan metode ini kelebihan beban. Elemen enumerasi disimpan sebagai string yang berisi nama elemen.

Perhatian

Jangan mengekspos RegistryKey objek sia-sia sehingga program berbahaya dapat membuat ribuan subkunci atau pasangan kunci/nilai yang tidak berarti. Misalnya, jangan izinkan penelepon untuk memasukkan kunci atau nilai arbitrer.

Lihat juga

Berlaku untuk

SetValue(String, Object, RegistryValueKind)

Sumber:
RegistryKey.cs

Mengatur nilai pasangan nama/nilai dalam kunci registri, menggunakan jenis data registri yang ditentukan.

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)

Parameter

name
String

Nama nilai yang akan disimpan.

value
Object

Data yang akan disimpan.

valueKind
RegistryValueKind

Jenis data registri yang digunakan saat menyimpan data.

Atribut

Pengecualian

valueadalah null.

Jenis value tidak cocok dengan tipe data registri yang ditentukan oleh valueKind, oleh karena itu data tidak dapat dikonversi dengan benar.

RegistryKey yang berisi nilai yang ditentukan ditutup (kunci tertutup tidak dapat diakses).

RegistryKey bersifat baca-saja, dan tidak dapat ditulis; misalnya, kunci belum dibuka dengan akses tulis.

Pengguna tidak memiliki izin yang diperlukan untuk membuat atau mengubah kunci registri.

Objek RegistryKey mewakili simpul tingkat akar, dan sistem operasinya adalah Windows 2000, Windows XP, atau Windows Server 2003.

Contoh

Contoh kode berikut membuat kunci pengujian dan menggunakan metode untuk menyimpan beberapa nilai, menentukan jenis data registri SetValue untuk setiap nilai. Contoh kemudian membaca pasangan nama/nilai dan menampilkannya ke konsol, menggunakan GetValueKind metode untuk menampilkan jenis data registri yang sesuai.

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

Keterangan

Karena banyak nilai yang dapat disimpan di setiap kunci dalam registri, Anda harus menggunakan name parameter untuk menentukan nilai tertentu yang ingin Anda tetapkan.

Catatan

Kunci registri dapat memiliki satu nilai yang tidak terkait dengan nama apa pun. Ketika nilai yang tidak disebutkan namanya ini ditampilkan di editor registri, string "(Default)" muncul alih-alih nama. Untuk mengatur nilai yang tidak disebutkan namanya ini, tentukan salah satu null atau string kosong ("") untuk name.

Untuk mengatur nilai dalam kunci, Anda harus membuka kunci dengan akses tulis. Setelah membuka kunci dengan akses tulis, Anda dapat mengubah salah satu pasangan nama/nilai dalam kunci tersebut.

Jika yang ditentukan name tidak ada di kunci, kunci dibuat, dan nilai terkait diatur ke value.

Catatan

Menentukan jenis Unknown data registri sama dengan menggunakan SetValue kelebihan beban.

Jika jenis yang ditentukan value tidak cocok dengan yang ditentukan valueKind, dan data tidak dapat dikonversi, ArgumentException akan dilemparkan. Misalnya, Anda dapat menyimpan System.Int64 sebagai RegistryValueKind.DWord, tetapi hanya jika nilainya kurang dari nilai System.Int32maksimum . Anda tidak dapat menyimpan nilai string tunggal sebagai RegistryValueKind.MultiString.

Catatan

Jika nilai kotak diteruskan untuk RegistryValueKind.DWord atau RegistryValueKind.QWord, konversi dilakukan menggunakan budaya invarian.

Perhatian

Jangan mengekspos RegistryKey objek sia-sia sehingga program berbahaya dapat membuat ribuan subkunci atau pasangan kunci/nilai yang tidak berarti. Misalnya, jangan izinkan penelepon untuk memasukkan kunci atau nilai arbitrer.

Lihat juga

Berlaku untuk