RegistryKey.SetValue Metoda

Definicja

Ustawia wartość pary name/value w kluczu rejestru. W zależności od przeciążenia typ danych rejestru jest określany z typu przechowywanych danych lub z określonego RegistryValueKindelementu .

Przeciążenia

SetValue(String, Object)

Ustawia określoną parę nazw/wartości.

SetValue(String, Object, RegistryValueKind)

Ustawia wartość pary nazw/wartości w kluczu rejestru przy użyciu określonego typu danych rejestru.

SetValue(String, Object)

Źródło:
RegistryKey.cs

Ustawia określoną parę nazw/wartości.

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)

Parametry

name
String

Nazwa wartości do przechowywania.

value
Object

Dane do przechowywania.

Wyjątki

value to null.

value jest nieobsługiwanym typem danych.

Element RegistryKey zawierający określoną wartość jest zamknięty (nie można uzyskać dostępu do kluczy zamkniętych).

Element RegistryKey jest tylko do odczytu i nie można go zapisać. Na przykład klucz nie został otwarty z dostępem do zapisu.

Użytkownik nie ma uprawnień wymaganych do tworzenia ani modyfikowania kluczy rejestru.

Obiekt RegistryKey reprezentuje węzeł na poziomie głównym, a system operacyjny to Windows 2000, Windows XP lub Windows Server 2003.

Przykłady

Poniższy przykład kodu pokazuje, jak SetValue metoda określa typ danych rejestru podczas ustawiania wartości. Przykład tworzy klucz testowy i dodaje wartości różnych typów danych do klucza. Następnie przykład odczytuje pary nazw/wartości i wyświetla je w konsoli przy użyciu GetValueKind metody w celu wyświetlenia odpowiednich typów danych rejestru.

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

Uwagi

Ponieważ wiele wartości może być przechowywanych w każdym kluczu w rejestrze, należy użyć parametru name , aby określić określoną wartość, którą chcesz ustawić.

Uwaga

Klucz rejestru może mieć jedną wartość, która nie jest skojarzona z żadną nazwą. Gdy ta nienazwana wartość jest wyświetlana w Edytorze rejestru, zamiast nazwy pojawia się ciąg „(Domyślna)”. Aby ustawić tę nienazwaną wartość, określ ciąg null pusty ("") dla parametru name.

Aby ustawić wartości w kluczu, musisz otworzyć klucz z dostępem do zapisu. Po otwarciu klucza z dostępem do zapisu można zmienić dowolną parę nazw/wartości w tym kluczu.

Jeśli określona wartość name nie istnieje w kluczu, zostanie utworzona, a skojarzona wartość ma wartość value.

To przeciążenie SetValue magazynów 64-bitowych liczb całkowitych jako ciągów (RegistryValueKind.String). Aby przechowywać 64-bitowe liczby jako RegistryValueKind.QWord wartości, użyj SetValue(String, Object, RegistryValueKind) przeciążenia, które określa RegistryValueKind.

To przeciążenie SetValue przechowuje wszystkie wartości ciągów jako RegistryValueKind.String, nawet jeśli zawierają rozszerzalne odwołania do zmiennych środowiskowych. Aby zapisać wartości ciągów jako ciągi rozszerzalne (RegistryValueKind.ExpandString), użyj SetValue(String, Object, RegistryValueKind) przeciążenia, które określa RegistryValueKind.

Typy liczbowe inne niż 32-bitowe liczby całkowite są przechowywane jako ciągi przez to przeciążenie metody. Elementy wyliczenia są przechowywane jako ciągi zawierające nazwy elementów.

Przestroga

Nie ujawniaj RegistryKey obiektów w taki sposób, że złośliwy program może tworzyć tysiące bezsensownych podkluczów lub par klucz/wartość. Na przykład nie wolno pozwalać obiektom wywołującym na wprowadzanie umownych kluczy ani wartości.

Zobacz też

Dotyczy

SetValue(String, Object, RegistryValueKind)

Źródło:
RegistryKey.cs

Ustawia wartość pary nazw/wartości w kluczu rejestru przy użyciu określonego typu danych rejestru.

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)

Parametry

name
String

Nazwa wartości, która ma być przechowywana.

value
Object

Dane do przechowywania.

valueKind
RegistryValueKind

Typ danych rejestru używany podczas przechowywania danych.

Atrybuty

Wyjątki

value to null.

Typ value nie pasuje do typu danych rejestru określonego przez valueKindmetodę , dlatego nie można poprawnie przekonwertować danych.

Element RegistryKey zawierający określoną wartość jest zamknięty (nie można uzyskać dostępu do kluczy zamkniętych).

Element RegistryKey jest tylko do odczytu i nie można go zapisać. Na przykład klucz nie został otwarty z dostępem do zapisu.

Użytkownik nie ma uprawnień wymaganych do tworzenia ani modyfikowania kluczy rejestru.

Obiekt RegistryKey reprezentuje węzeł na poziomie głównym, a system operacyjny to Windows 2000, Windows XP lub Windows Server 2003.

Przykłady

Poniższy przykład kodu tworzy klucz testowy i używa SetValue metody do przechowywania kilku wartości, określając typ danych rejestru dla każdej wartości. Następnie przykład odczytuje pary nazw/wartości i wyświetla je w konsoli przy użyciu GetValueKind metody w celu wyświetlenia odpowiednich typów danych rejestru.

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

Uwagi

Ponieważ wiele wartości może być przechowywanych w każdym kluczu w rejestrze, należy użyć parametru name , aby określić określoną wartość, którą chcesz ustawić.

Uwaga

Klucz rejestru może mieć jedną wartość, która nie jest skojarzona z żadną nazwą. Gdy ta nienazwana wartość jest wyświetlana w Edytorze rejestru, zamiast nazwy pojawia się ciąg „(Domyślna)”. Aby ustawić tę nienazwaną wartość, określ ciąg null pusty ("") dla parametru name.

Aby ustawić wartości w kluczu, musisz otworzyć klucz z dostępem do zapisu. Po otwarciu klucza z dostępem do zapisu można zmienić dowolną parę nazw/wartości w tym kluczu.

Jeśli określona wartość name nie istnieje w kluczu, zostanie utworzona, a skojarzona wartość ma wartość value.

Uwaga

Określanie typu Unknown danych rejestru jest takie samo jak przy użyciu SetValue przeciążenia.

Jeśli typ określonego value elementu jest niezgodny z określonym valueKindelementem , a nie można przekonwertować danych, ArgumentException zostanie zgłoszony. Można na przykład przechowywać jako System.Int64RegistryValueKind.DWordwartość , ale tylko wtedy, gdy jej wartość jest mniejsza niż maksymalna wartość System.Int32elementu . Nie można przechowywać pojedynczej wartości ciągu jako RegistryValueKind.MultiString.

Uwaga

Jeśli wartości pola są przekazywane dla RegistryValueKind.DWord lub RegistryValueKind.QWord, konwersja jest wykonywana przy użyciu niezmiennej kultury.

Przestroga

Nie ujawniaj RegistryKey obiektów w taki sposób, że złośliwy program może tworzyć tysiące bezsensownych podkluczów lub par klucz/wartość. Na przykład nie wolno pozwalać obiektom wywołującym na wprowadzanie umownych kluczy ani wartości.

Zobacz też

Dotyczy