Edit

Share via


RegistryKey.SetValue Method

Definition

Sets the value of a name/value pair in the registry key. Depending on the overload, the registry data type is determined from the type of data being stored or from a specified RegistryValueKind.

Overloads

SetValue(String, Object)

Sets the specified name/value pair.

SetValue(String, Object, RegistryValueKind)

Sets the value of a name/value pair in the registry key, using the specified registry data type.

SetValue(String, Object)

Source:
RegistryKey.cs

Sets the specified name/value pair.

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)

Parameters

name
String

The name of the value to store.

value
Object

The data to be stored.

Exceptions

value is null.

value is an unsupported data type.

The RegistryKey that contains the specified value is closed (closed keys cannot be accessed).

The RegistryKey is read-only, and cannot be written to; for example, the key has not been opened with write access.

The user does not have the permissions required to create or modify registry keys.

The RegistryKey object represents a root-level node, and the operating system is Windows 2000, Windows XP, or Windows Server 2003.

Examples

The following code example shows how the SetValue method determines the registry data type when it sets values. The example creates a test key and adds values of different data types to the key. The example then reads the name/value pairs and displays them to the console, using the GetValueKind method to display the corresponding registry data types.

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

Remarks

Because many values can be stored in each key in the registry, you must use the name parameter to specify the particular value you want to set.

Note

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. To set this unnamed value, specify either null or the empty string ("") for name.

In order to set values in a key, you must open the key with write access. After you have opened a key with write access, you can change any of the name/value pairs in that key.

If the specified name does not exist in the key, it is created and the associated value is set to value.

This overload of SetValue stores 64-bit integers as strings (RegistryValueKind.String). To store 64-bit numbers as RegistryValueKind.QWord values, use the SetValue(String, Object, RegistryValueKind) overload that specifies RegistryValueKind.

This overload of SetValue stores all string values as RegistryValueKind.String, even if they contain expandable references to environment variables. To save string values as expandable strings (RegistryValueKind.ExpandString), use the SetValue(String, Object, RegistryValueKind) overload that specifies RegistryValueKind.

Numeric types other than 32-bit integers are stored as strings by this method overload. Enumeration elements are stored as strings containing the element names.

Caution

Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. For example, do not allow callers to enter arbitrary keys or values.

See also

Applies to

SetValue(String, Object, RegistryValueKind)

Source:
RegistryKey.cs

Sets the value of a name/value pair in the registry key, using the specified registry data type.

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)

Parameters

name
String

The name of the value to be stored.

value
Object

The data to be stored.

valueKind
RegistryValueKind

The registry data type to use when storing the data.

Attributes

Exceptions

value is null.

The type of value did not match the registry data type specified by valueKind, therefore the data could not be converted properly.

The RegistryKey that contains the specified value is closed (closed keys cannot be accessed).

The RegistryKey is read-only, and cannot be written to; for example, the key has not been opened with write access.

The user does not have the permissions required to create or modify registry keys.

The RegistryKey object represents a root-level node, and the operating system is Windows 2000, Windows XP, or Windows Server 2003.

Examples

The following code example creates a test key and uses the SetValue method to store several values, specifying the registry data type for each value. The example then reads the name/value pairs and displays them to the console, using the GetValueKind method to display 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.***]

Remarks

Because many values can be stored in each key in the registry, you must use the name parameter to specify the particular value you want to set.

Note

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. To set this unnamed value, specify either null or the empty string ("") for name.

In order to set values in a key, you must open the key with write access. After you have opened a key with write access, you can change any of the name/value pairs in that key.

If the specified name does not exist in the key, it is created, and the associated value is set to value.

Note

Specifying the registry data type Unknown is the same as using the SetValue overload.

If the type of the specified value does not match the specified valueKind, and the data cannot be converted, ArgumentException is thrown. For example, you can store a System.Int64 as a RegistryValueKind.DWord, but only if its value is less than the maximum value of a System.Int32. You cannot store a single string value as a RegistryValueKind.MultiString.

Note

If boxed values are passed for RegistryValueKind.DWord or RegistryValueKind.QWord, the conversion is done using the invariant culture.

Caution

Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. For example, do not allow callers to enter arbitrary keys or values.

See also

Applies to