RegistryKey.SetValue 方法

定义

设置注册表项中的名称/值对的值。Sets the value of a name/value pair in the registry key. 从所存储数据的类型或指定的 RegistryValueKind 确定注册表数据类型,具体取决于重载。Depending on the overload, the registry data type is determined from the type of data being stored or from a specified RegistryValueKind.

重载

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)

设置指定的名称/值对。Sets the specified name/value pair.

public:
 void SetValue(System::String ^ name, System::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

要存储的值的名称。The name of the value to store.

value
Object

要存储的数据。The data to be stored.

异常

valuenullvalue is null.

value 不是受支持的数据类型。value is an unsupported data type.

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

RegistryKey 只读,因此无法写入;例如,项不是用写访问权限打开的。The RegistryKey is read-only, and cannot be written to; for example, the key has not been opened with write access.

- 或 --or- RegistryKey 对象表示根级别节点,操作系统为 Windows Millennium Edition 或 Windows 98。The RegistryKey object represents a root-level node, and the operating system is Windows Millennium Edition or Windows 98.

用户没有创建或修改注册表项所需的权限。The user does not have the permissions required to create or modify registry keys.

RegistryKey 对象表示根级别节点,操作系统为 Windows 2000、Windows XP 或 Windows Server 2003。The RegistryKey object represents a root-level node, and the operating system is Windows 2000, Windows XP, or Windows Server 2003.

示例

下面的代码示例演示 SetValue 方法在设置值时如何确定注册表数据类型。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. 然后,该示例将读取名称/值对,并将其显示在控制台中,方法是使用 GetValueKind 方法来显示相应的注册表数据类型。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

注解

由于注册表中的每个键都可以存储许多值,因此必须使用 name 参数来指定要设置的特定值。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.

备注

注册表项可以有一个不与任何名称关联的值。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 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.

如果密钥中不存在指定的 name,则将创建它并将关联的值设置为 valueIf the specified name does not exist in the key, it is created and the associated value is set to value.

SetValue 的此重载将64位整数存储为字符串(RegistryValueKind.String)。This overload of SetValue stores 64-bit integers as strings (RegistryValueKind.String). 若要将64位数字存储为 RegistryValueKind.QWord 值,请使用指定 RegistryValueKindSetValue(String, Object, RegistryValueKind) 重载。To store 64-bit numbers as RegistryValueKind.QWord values, use the SetValue(String, Object, RegistryValueKind) overload that specifies RegistryValueKind.

SetValue 的此重载将所有字符串值存储为 RegistryValueKind.String,即使它们包含对环境变量的可展开引用。This overload of SetValue stores all string values as RegistryValueKind.String, even if they contain expandable references to environment variables. 若要将字符串值保存为可扩充字符串(RegistryValueKind.ExpandString),请使用指定 RegistryValueKindSetValue(String, Object, RegistryValueKind) 重载。To save string values as expandable strings (RegistryValueKind.ExpandString), use the SetValue(String, Object, RegistryValueKind) overload that specifies RegistryValueKind.

此方法重载将非32位整数以外的数值类型存储为字符串。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.

注意

不要以这种方式公开 RegistryKey 对象,恶意程序可能会创建数千个无意义子项或键/值对。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.

备注

在 Windows 98 和 Windows Millennium Edition 中,注册表不是 Unicode,并且并非所有 Unicode 字符对于所有代码页都有效。On Windows 98 and Windows Millennium Edition the registry is not Unicode, and not all Unicode characters are valid for all code pages. 对于当前代码页无效的 Unicode 字符被替换为最佳可用匹配项。A Unicode character that is invalid for the current code page is replaced by the best available match. 不引发异常。No exception is thrown.

安全性

RegistryPermission
如果指定的注册表项存在,则对其进行修改,如果该注册表项不存在,则创建该注册表项。to modify the specified registry key if it exists, or to create the registry key if it does not already exist. 关联的枚举: WriteCreateAssociated enumerations: Write, Create

SecurityPermission
用于访问指定注册表项(如果它是远程密钥)的功能。for the ability to access the specified registry key if it is a remote key. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

另请参阅

SetValue(String, Object, RegistryValueKind)

使用指定的注册表数据类型设置注册表项中的名称/值对的值。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);
[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
Public Sub SetValue (name As String, value As Object, valueKind As RegistryValueKind)

参数

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.

属性

异常

valuenullvalue is null.

value 的类型与 valueKind 指定的注册表数据类型不匹配,因此,未能正确转换该数据。The type of value did not match the registry data type specified by valueKind, therefore the data could not be converted properly.

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

RegistryKey 只读,因此无法写入;例如,项不是用写访问权限打开的。The RegistryKey is read-only, and cannot be written to; for example, the key has not been opened with write access.

- 或 --or- RegistryKey 对象表示根级别节点,操作系统为 Windows Millennium Edition 或 Windows 98。The RegistryKey object represents a root-level node, and the operating system is Windows Millennium Edition or Windows 98.

用户没有创建或修改注册表项所需的权限。The user does not have the permissions required to create or modify registry keys.

RegistryKey 对象表示根级别节点,操作系统为 Windows 2000、Windows XP 或 Windows Server 2003。The RegistryKey object represents a root-level node, and the operating system is Windows 2000, Windows XP, or Windows Server 2003.

示例

下面的代码示例创建一个测试键,并使用 SetValue 方法存储多个值,并为每个值指定注册表数据类型。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. 然后,该示例将读取名称/值对,并将其显示在控制台中,方法是使用 GetValueKind 方法来显示相应的注册表数据类型。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.***]

注解

由于注册表中的每个键都可以存储许多值,因此必须使用 name 参数来指定要设置的特定值。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.

备注

注册表项可以有一个不与任何名称关联的值。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 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.

如果指定的 name 在密钥中不存在,则将创建该,并将关联的值设置为 valueIf the specified name does not exist in the key, it is created, and the associated value is set to value.

备注

指定注册表数据类型 Unknown 与使用 SetValue 重载相同。Specifying the registry data type Unknown is the same as using the SetValue overload.

如果指定 value 的类型与指定的 valueKind不匹配,并且数据无法转换,则会引发 ArgumentExceptionIf the type of the specified value does not match the specified valueKind, and the data cannot be converted, ArgumentException is thrown. 例如,你可以将 System.Int64 存储为 RegistryValueKind.DWord,但前提是它的值小于 System.Int32的最大值。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. 不能将单个字符串值存储为 RegistryValueKind.MultiStringYou cannot store a single string value as a RegistryValueKind.MultiString.

备注

如果为 RegistryValueKind.DWordRegistryValueKind.QWord传递装箱值,则将使用固定区域性完成转换。If boxed values are passed for RegistryValueKind.DWord or RegistryValueKind.QWord, the conversion is done using the invariant culture.

注意

不要以这种方式公开 RegistryKey 对象,恶意程序可能会创建数千个无意义子项或键/值对。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.

备注

在 Windows 98 和 Windows Millennium Edition 中,注册表不是 Unicode,并且并非所有 Unicode 字符对于所有代码页都有效。On Windows 98 and Windows Millennium Edition the registry is not Unicode, and not all Unicode characters are valid for all code pages. 对于当前代码页无效的 Unicode 字符被替换为最佳可用匹配项。A Unicode character that is invalid for the current code page is replaced by the best available match. 不引发异常。No exception is thrown.

安全性

RegistryPermission
如果指定的注册表项存在,则对其进行修改,如果该注册表项不存在,则创建该注册表项。to modify the specified registry key if it exists, or to create the registry key if it does not already exist. 关联的枚举: WriteCreateAssociated enumerations: Write, Create

SecurityPermission
用于访问指定注册表项(如果它是远程密钥)的功能。for the ability to access the specified registry key if it is a remote key. 关联的枚举: UnmanagedCodeAssociated enumeration: UnmanagedCode

另请参阅

适用于