Registry.SetValue 方法

定义

设置注册表项中的名称/值对的值。Sets the value of a name/value pair in a registry key.

重载

SetValue(String, String, Object)

设置指定的注册表项的指定名称/值对。Sets the specified name/value pair on the specified registry key. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

SetValue(String, String, Object, RegistryValueKind)

通过使用指定的注册表数据类型,设置该指定的注册表项的名称/值对。Sets the name/value pair on the specified registry key, using the specified registry data type. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

示例

下面的代码示例将多个数据类型的值存储在一个示例键中,按其创建键,然后检索并显示这些值。The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. 该示例演示了在名称/值对不存在时,存储和检索默认(无名称)名称/值对,并使用 defaultValueThe example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.

using namespace System;
using namespace Microsoft::Win32;

int main()
{   
    // The name of the key must include a valid root.
    String^ userRoot = "HKEY_CURRENT_USER";
    String^ subKey = "RegistrySetValueExample2";
    String^ keyName = String::Concat(userRoot, "\\", subKey);
    
    // An int value can be stored without specifying the
    // registry data type, but Int64 values will be stored
    // as strings unless you specify the type. Note that
    // the int is stored in the default name/value
    // pair.
    Registry::SetValue(keyName, "", 5280);
    Registry::SetValue(keyName, "TestInt64", 12345678901234, 
        RegistryValueKind::QWord);
    
    // Strings with expandable environment variables are
    // stored as ordinary strings unless you specify the
    // data type.
    Registry::SetValue(keyName, "TestExpand", "My path: %path%");
    Registry::SetValue(keyName, "TestExpand2", "My path: %path%", 
        RegistryValueKind::ExpandString);
    
    // Arrays of strings are stored automatically as 
    // MultiString. Similarly, arrays of Byte are stored
    // automatically as Binary.
    array<String^>^ strings  = {"One", "Two", "Three"};
    Registry::SetValue(keyName, "TestArray", strings);
    
    // Your default value is returned if the name/value pair
    // does not exist.
    String^ noSuch = (String^)Registry::GetValue(keyName, 
        "NoSuchName", 
        "Return this default if NoSuchName does not exist.");
    Console::WriteLine("\r\nNoSuchName: {0}", noSuch);
    
    // Retrieve the int and Int64 values, specifying 
    // numeric default values in case the name/value pairs
    // do not exist. The int value is retrieved from the
    // default (nameless) name/value pair for the key.
    int testInteger = (int)Registry::GetValue(keyName, "", -1);
    Console::WriteLine("(Default): {0}", testInteger);
    long long testInt64 = (long long)Registry::GetValue(keyName, 
        "TestInt64", System::Int64::MinValue);
    Console::WriteLine("TestInt64: {0}", testInt64);
    
    // When retrieving a MultiString value, you can specify
    // an array for the default return value. 
    array<String^>^ testArray = (array<String^>^)Registry::GetValue(
        keyName, "TestArray", 
        gcnew array<String^> {"Default if TestArray does not exist."});
    for (int i = 0; i < testArray->Length; i++)
    {
        Console::WriteLine("TestArray({0}): {1}", i, testArray[i]);
    }
    
    // A string with embedded environment variables is not
    // expanded if it was stored as an ordinary string.
    String^ testExpand = (String^)Registry::GetValue(keyName, 
        "TestExpand", "Default if TestExpand does not exist.");
    Console::WriteLine("TestExpand: {0}", testExpand);
    
    // A string stored as ExpandString is expanded.
    String^ testExpand2 = (String^)Registry::GetValue(keyName, 
        "TestExpand2", "Default if TestExpand2 does not exist.");
    Console::WriteLine(
        "TestExpand2: {0}...", testExpand2->Substring(0, 40));
    Console::WriteLine(
        "\r\nUse the registry editor to examine the key.");
    Console::WriteLine("Press the Enter key to delete the key.");
    Console::ReadLine();
    Registry::CurrentUser->DeleteSubKey(subKey);
}
//
// This code example produces output similar to the following:
//
// NoSuchName: Return this default if NoSuchName does not exist.
// (Default): 5280
// TestInt64: 12345678901234
// TestArray(0): One
// TestArray(1): Two
// TestArray(2): Three
// TestExpand: My path: %path%
// TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
// Use the registry editor to examine the key.
// Press the Enter key to delete the key.
using System;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // The name of the key must include a valid root.
        const string userRoot = "HKEY_CURRENT_USER";
        const string subkey = "RegistrySetValueExample";
        const string keyName = userRoot + "\\" + subkey;

        // An int value can be stored without specifying the
        // registry data type, but long values will be stored
        // as strings unless you specify the type. Note that
        // the int is stored in the default name/value
        // pair.
        Registry.SetValue(keyName, "", 5280);
        Registry.SetValue(keyName, "TestLong", 12345678901234,
            RegistryValueKind.QWord);

        // Strings with expandable environment variables are
        // stored as ordinary strings unless you specify the
        // data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%");
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%",
            RegistryValueKind.ExpandString);

        // Arrays of strings are stored automatically as 
        // MultiString. Similarly, arrays of Byte are stored
        // automatically as Binary.
        string[] strings = {"One", "Two", "Three"};
        Registry.SetValue(keyName, "TestArray", strings);

        // Your default value is returned if the name/value pair
        // does not exist.
        string noSuch = (string) Registry.GetValue(keyName, 
            "NoSuchName",
            "Return this default if NoSuchName does not exist.");
        Console.WriteLine("\r\nNoSuchName: {0}", noSuch);

        // Retrieve the int and long values, specifying 
        // numeric default values in case the name/value pairs
        // do not exist. The int value is retrieved from the
        // default (nameless) name/value pair for the key.
        int tInteger = (int) Registry.GetValue(keyName, "", -1);
        Console.WriteLine("(Default): {0}", tInteger);
        long tLong = (long) Registry.GetValue(keyName, "TestLong",
            long.MinValue);
        Console.WriteLine("TestLong: {0}", tLong);

        // When retrieving a MultiString value, you can specify
        // an array for the default return value. 
        string[] tArray = (string[]) Registry.GetValue(keyName,
            "TestArray",
            new string[] {"Default if TestArray does not exist."});
        for(int i=0; i<tArray.Length; i++)
        {
            Console.WriteLine("TestArray({0}): {1}", i, tArray[i]);
        }

        // A string with embedded environment variables is not
        // expanded if it was stored as an ordinary string.
        string tExpand = (string) Registry.GetValue(keyName,
             "TestExpand", 
             "Default if TestExpand does not exist.");
        Console.WriteLine("TestExpand: {0}", tExpand);

        // A string stored as ExpandString is expanded.
        string tExpand2 = (string) Registry.GetValue(keyName,
            "TestExpand2",
            "Default if TestExpand2 does not exist.");
        Console.WriteLine("TestExpand2: {0}...",
            tExpand2.Substring(0, 40));

        Console.WriteLine("\r\nUse the registry editor to examine the key.");
        Console.WriteLine("Press the Enter key to delete the key.");
        Console.ReadLine();
        Registry.CurrentUser.DeleteSubKey(subkey);
    }
}
//
// This code example produces output similar to the following:
//
//NoSuchName: Return this default if NoSuchName does not exist.
//(Default): 5280
//TestLong: 12345678901234
//TestArray(0): One
//TestArray(1): Two
//TestArray(2): Three
//TestExpand: My path: %path%
//TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
//Use the registry editor to examine the key.
//Press the Enter key to delete the key.
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' The name of the key must include a valid root.
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "RegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        ' Integer values can be stored without specifying the
        ' registry data type, but Long values will be stored
        ' as strings unless you specify the type. Note that
        ' the integer is stored in the default name/value
        ' pair.
        Registry.SetValue(keyName, "", 5280)
        Registry.SetValue(keyName, "TestLong", 12345678901234, _
            RegistryValueKind.QWord)

        ' Strings with expandable environment variables are
        ' stored as ordinary strings unless you specify the
        ' data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%")
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%", _
            RegistryValueKind.ExpandString)

        ' Arrays of strings are stored automatically as 
        ' MultiString. Similarly, arrays of Byte are stored
        ' automatically as Binary.
        Dim strings() As String = {"One", "Two", "Three"}
        Registry.SetValue(keyName, "TestArray", strings)

        ' Your default value is returned if the name/value pair
        ' does not exist.
        Dim noSuch As String = _
            Registry.GetValue(keyName, "NoSuchName", _
            "Return this default if NoSuchName does not exist.")
        Console.WriteLine(vbCrLf & "NoSuchName: {0}", noSuch)

        ' Retrieve the Integer and Long values, specifying 
        ' numeric default values in case the name/value pairs
        ' do not exist. The Integer value is retrieved from the
        ' default (nameless) name/value pair for the key.
        Dim tInteger As Integer = _
            Registry.GetValue(keyName, "", -1)
        Console.WriteLine("(Default): {0}", tInteger)
        Dim tLong As Long = Registry.GetValue(keyName, _
             "TestLong", Long.MinValue)
        Console.WriteLine("TestLong: {0}", tLong)

        ' When retrieving a MultiString value, you can specify
        ' an array for the default return value. The value is
        ' declared inline, but could also be declared as:
        ' Dim default() As String = {"Default value."}
        '
        Dim tArray() As String = _
            Registry.GetValue(keyName, "TestArray", _
            New String() {"Default if TestArray does not exist."})
        For i As Integer = 0 To tArray.Length - 1
            Console.WriteLine("TestArray({0}): {1}", i, tArray(i))
        Next

        ' A string with embedded environment variables is not
        ' expanded if it was stored as an ordinary string.
        Dim tExpand As String = Registry.GetValue(keyName, _
             "TestExpand", "Default if TestExpand does not exist.")
        Console.WriteLine("TestExpand: {0}", tExpand)

        ' A string stored as ExpandString is expanded.
        Dim tExpand2 As String = Registry.GetValue(keyName, _
             "TestExpand2", "Default if TestExpand2 does not exist.")
        Console.WriteLine("TestExpand2: {0}...", _
            tExpand2.Substring(0, 40))

        Console.WriteLine(vbCrLf & _
            "Use the registry editor to examine the key.")
        Console.WriteLine("Press the Enter key to delete the key.")
        Console.ReadLine()
        Registry.CurrentUser.DeleteSubKey(subkey)
    End Sub
End Class
'
' This code example produces output similar to the following:
'
'NoSuchName: Return this default if NoSuchName does not exist.
'(Default): 5280
'TestLong: 12345678901234
'TestArray(0): One
'TestArray(1): Two
'TestArray(2): Three
'TestExpand: My path: %path%
'TestExpand2: My path: D:\Program Files\Microsoft.NET\...
'
'Use the registry editor to examine the key.
'Press the Enter key to delete the key.

SetValue(String, String, Object)

设置指定的注册表项的指定名称/值对。Sets the specified name/value pair on the specified registry key. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

public:
 static void SetValue(System::String ^ keyName, System::String ^ valueName, System::Object ^ value);
public static void SetValue (string keyName, string valueName, object value);
static member SetValue : string * string * obj -> unit
Public Shared Sub SetValue (keyName As String, valueName As String, value As Object)

参数

keyName
String

以有效注册表根(如“HKEY_CURRENT_USER”)开头的键的完整注册表路径。The full registry path of the key, beginning with a valid registry root, such as "HKEY_CURRENT_USER".

valueName
String

名称/值对的名称。The name of the name/value pair.

value
Object

要存储的值。The value to be stored.

异常

valuenullvalue is null.

keyName 未以有效注册表根开头。keyName does not begin with a valid registry root.

- 或 --or- keyName 的长度超过了允许的最大长度(255 个字符)。keyName is longer than the maximum length allowed (255 characters).

RegistryKey 是只读的,因此无法对其写入;例如,它是根级节点。The RegistryKey is read-only, and thus cannot be written to; for example, it is a root-level node.

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

示例

下面的代码示例将多个数据类型的值存储在一个示例键中,按其创建键,然后检索并显示这些值。The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. 该示例演示了在名称/值对不存在时,存储和检索默认(无名称)名称/值对,并使用 defaultValueThe example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.

using namespace System;
using namespace Microsoft::Win32;

int main()
{   
    // The name of the key must include a valid root.
    String^ userRoot = "HKEY_CURRENT_USER";
    String^ subKey = "RegistrySetValueExample2";
    String^ keyName = String::Concat(userRoot, "\\", subKey);
    
    // An int value can be stored without specifying the
    // registry data type, but Int64 values will be stored
    // as strings unless you specify the type. Note that
    // the int is stored in the default name/value
    // pair.
    Registry::SetValue(keyName, "", 5280);
    Registry::SetValue(keyName, "TestInt64", 12345678901234, 
        RegistryValueKind::QWord);
    
    // Strings with expandable environment variables are
    // stored as ordinary strings unless you specify the
    // data type.
    Registry::SetValue(keyName, "TestExpand", "My path: %path%");
    Registry::SetValue(keyName, "TestExpand2", "My path: %path%", 
        RegistryValueKind::ExpandString);
    
    // Arrays of strings are stored automatically as 
    // MultiString. Similarly, arrays of Byte are stored
    // automatically as Binary.
    array<String^>^ strings  = {"One", "Two", "Three"};
    Registry::SetValue(keyName, "TestArray", strings);
    
    // Your default value is returned if the name/value pair
    // does not exist.
    String^ noSuch = (String^)Registry::GetValue(keyName, 
        "NoSuchName", 
        "Return this default if NoSuchName does not exist.");
    Console::WriteLine("\r\nNoSuchName: {0}", noSuch);
    
    // Retrieve the int and Int64 values, specifying 
    // numeric default values in case the name/value pairs
    // do not exist. The int value is retrieved from the
    // default (nameless) name/value pair for the key.
    int testInteger = (int)Registry::GetValue(keyName, "", -1);
    Console::WriteLine("(Default): {0}", testInteger);
    long long testInt64 = (long long)Registry::GetValue(keyName, 
        "TestInt64", System::Int64::MinValue);
    Console::WriteLine("TestInt64: {0}", testInt64);
    
    // When retrieving a MultiString value, you can specify
    // an array for the default return value. 
    array<String^>^ testArray = (array<String^>^)Registry::GetValue(
        keyName, "TestArray", 
        gcnew array<String^> {"Default if TestArray does not exist."});
    for (int i = 0; i < testArray->Length; i++)
    {
        Console::WriteLine("TestArray({0}): {1}", i, testArray[i]);
    }
    
    // A string with embedded environment variables is not
    // expanded if it was stored as an ordinary string.
    String^ testExpand = (String^)Registry::GetValue(keyName, 
        "TestExpand", "Default if TestExpand does not exist.");
    Console::WriteLine("TestExpand: {0}", testExpand);
    
    // A string stored as ExpandString is expanded.
    String^ testExpand2 = (String^)Registry::GetValue(keyName, 
        "TestExpand2", "Default if TestExpand2 does not exist.");
    Console::WriteLine(
        "TestExpand2: {0}...", testExpand2->Substring(0, 40));
    Console::WriteLine(
        "\r\nUse the registry editor to examine the key.");
    Console::WriteLine("Press the Enter key to delete the key.");
    Console::ReadLine();
    Registry::CurrentUser->DeleteSubKey(subKey);
}
//
// This code example produces output similar to the following:
//
// NoSuchName: Return this default if NoSuchName does not exist.
// (Default): 5280
// TestInt64: 12345678901234
// TestArray(0): One
// TestArray(1): Two
// TestArray(2): Three
// TestExpand: My path: %path%
// TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
// Use the registry editor to examine the key.
// Press the Enter key to delete the key.
using System;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // The name of the key must include a valid root.
        const string userRoot = "HKEY_CURRENT_USER";
        const string subkey = "RegistrySetValueExample";
        const string keyName = userRoot + "\\" + subkey;

        // An int value can be stored without specifying the
        // registry data type, but long values will be stored
        // as strings unless you specify the type. Note that
        // the int is stored in the default name/value
        // pair.
        Registry.SetValue(keyName, "", 5280);
        Registry.SetValue(keyName, "TestLong", 12345678901234,
            RegistryValueKind.QWord);

        // Strings with expandable environment variables are
        // stored as ordinary strings unless you specify the
        // data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%");
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%",
            RegistryValueKind.ExpandString);

        // Arrays of strings are stored automatically as 
        // MultiString. Similarly, arrays of Byte are stored
        // automatically as Binary.
        string[] strings = {"One", "Two", "Three"};
        Registry.SetValue(keyName, "TestArray", strings);

        // Your default value is returned if the name/value pair
        // does not exist.
        string noSuch = (string) Registry.GetValue(keyName, 
            "NoSuchName",
            "Return this default if NoSuchName does not exist.");
        Console.WriteLine("\r\nNoSuchName: {0}", noSuch);

        // Retrieve the int and long values, specifying 
        // numeric default values in case the name/value pairs
        // do not exist. The int value is retrieved from the
        // default (nameless) name/value pair for the key.
        int tInteger = (int) Registry.GetValue(keyName, "", -1);
        Console.WriteLine("(Default): {0}", tInteger);
        long tLong = (long) Registry.GetValue(keyName, "TestLong",
            long.MinValue);
        Console.WriteLine("TestLong: {0}", tLong);

        // When retrieving a MultiString value, you can specify
        // an array for the default return value. 
        string[] tArray = (string[]) Registry.GetValue(keyName,
            "TestArray",
            new string[] {"Default if TestArray does not exist."});
        for(int i=0; i<tArray.Length; i++)
        {
            Console.WriteLine("TestArray({0}): {1}", i, tArray[i]);
        }

        // A string with embedded environment variables is not
        // expanded if it was stored as an ordinary string.
        string tExpand = (string) Registry.GetValue(keyName,
             "TestExpand", 
             "Default if TestExpand does not exist.");
        Console.WriteLine("TestExpand: {0}", tExpand);

        // A string stored as ExpandString is expanded.
        string tExpand2 = (string) Registry.GetValue(keyName,
            "TestExpand2",
            "Default if TestExpand2 does not exist.");
        Console.WriteLine("TestExpand2: {0}...",
            tExpand2.Substring(0, 40));

        Console.WriteLine("\r\nUse the registry editor to examine the key.");
        Console.WriteLine("Press the Enter key to delete the key.");
        Console.ReadLine();
        Registry.CurrentUser.DeleteSubKey(subkey);
    }
}
//
// This code example produces output similar to the following:
//
//NoSuchName: Return this default if NoSuchName does not exist.
//(Default): 5280
//TestLong: 12345678901234
//TestArray(0): One
//TestArray(1): Two
//TestArray(2): Three
//TestExpand: My path: %path%
//TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
//Use the registry editor to examine the key.
//Press the Enter key to delete the key.
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' The name of the key must include a valid root.
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "RegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        ' Integer values can be stored without specifying the
        ' registry data type, but Long values will be stored
        ' as strings unless you specify the type. Note that
        ' the integer is stored in the default name/value
        ' pair.
        Registry.SetValue(keyName, "", 5280)
        Registry.SetValue(keyName, "TestLong", 12345678901234, _
            RegistryValueKind.QWord)

        ' Strings with expandable environment variables are
        ' stored as ordinary strings unless you specify the
        ' data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%")
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%", _
            RegistryValueKind.ExpandString)

        ' Arrays of strings are stored automatically as 
        ' MultiString. Similarly, arrays of Byte are stored
        ' automatically as Binary.
        Dim strings() As String = {"One", "Two", "Three"}
        Registry.SetValue(keyName, "TestArray", strings)

        ' Your default value is returned if the name/value pair
        ' does not exist.
        Dim noSuch As String = _
            Registry.GetValue(keyName, "NoSuchName", _
            "Return this default if NoSuchName does not exist.")
        Console.WriteLine(vbCrLf & "NoSuchName: {0}", noSuch)

        ' Retrieve the Integer and Long values, specifying 
        ' numeric default values in case the name/value pairs
        ' do not exist. The Integer value is retrieved from the
        ' default (nameless) name/value pair for the key.
        Dim tInteger As Integer = _
            Registry.GetValue(keyName, "", -1)
        Console.WriteLine("(Default): {0}", tInteger)
        Dim tLong As Long = Registry.GetValue(keyName, _
             "TestLong", Long.MinValue)
        Console.WriteLine("TestLong: {0}", tLong)

        ' When retrieving a MultiString value, you can specify
        ' an array for the default return value. The value is
        ' declared inline, but could also be declared as:
        ' Dim default() As String = {"Default value."}
        '
        Dim tArray() As String = _
            Registry.GetValue(keyName, "TestArray", _
            New String() {"Default if TestArray does not exist."})
        For i As Integer = 0 To tArray.Length - 1
            Console.WriteLine("TestArray({0}): {1}", i, tArray(i))
        Next

        ' A string with embedded environment variables is not
        ' expanded if it was stored as an ordinary string.
        Dim tExpand As String = Registry.GetValue(keyName, _
             "TestExpand", "Default if TestExpand does not exist.")
        Console.WriteLine("TestExpand: {0}", tExpand)

        ' A string stored as ExpandString is expanded.
        Dim tExpand2 As String = Registry.GetValue(keyName, _
             "TestExpand2", "Default if TestExpand2 does not exist.")
        Console.WriteLine("TestExpand2: {0}...", _
            tExpand2.Substring(0, 40))

        Console.WriteLine(vbCrLf & _
            "Use the registry editor to examine the key.")
        Console.WriteLine("Press the Enter key to delete the key.")
        Console.ReadLine()
        Registry.CurrentUser.DeleteSubKey(subkey)
    End Sub
End Class
'
' This code example produces output similar to the following:
'
'NoSuchName: Return this default if NoSuchName does not exist.
'(Default): 5280
'TestLong: 12345678901234
'TestArray(0): One
'TestArray(1): Two
'TestArray(2): Three
'TestExpand: My path: %path%
'TestExpand2: My path: D:\Program Files\Microsoft.NET\...
'
'Use the registry editor to examine the key.
'Press the Enter key to delete the key.

注解

.NET Framework 4.NET Framework 4开始,valueName 参数不再限制在最多255个字符之间;但 keyName 参数将继续具有255字符的限制。Starting with the .NET Framework 4.NET Framework 4, the valueName parameter is no longer restricted to a maximum of 255 characters; however, the keyName parameter continues to have the 255-character restriction.

由于注册表中的每个键都可以存储许多值,因此必须使用 valueName 参数来指定要设置的特定值。Because many values can be stored in each key in the registry, you must use the valueName parameter to specify the particular value you want to set.

备注

注册表项可以包含一个不与任何名称关联的值。A registry key can contain 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. 若要设置此未命名值,请为 valueName指定 null 或空字符串("")。To set this unnamed value, specify either null or the empty string ("") for valueName.

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

如果 keyName 指定的子项不存在,则会在指定的根中创建该子项。If keyName specifies a subkey that does not exist, the subkey is created in the specified root. 例如,在 Visual Basic 字符串 "HKEY_CURRENT_USER \MyTestKey" 在 HKEY_CURRENT_USER 根中创建子项 "MyTestKey"。For example, in Visual Basic the string "HKEY_CURRENT_USER\MyTestKey" creates the subkey "MyTestKey" in the HKEY_CURRENT_USER root. 字符串 "HKEY_CURRENT_USER \MyTestKey\Key2\Key3" 创建嵌套子项 "MyTestKey"、"MyTestKey\Key2" 和 "MyTestKey\Key2\Key3"。The string "HKEY_CURRENT_USER\MyTestKey\Key2\Key3" creates the nested subkeys "MyTestKey", "MyTestKey\Key2", and "MyTestKey\Key2\Key3".

有效的根名称包括 HKEY_CURRENT_USER、HKEY_LOCAL_MACHINE、HKEY_CLASSES_ROOT、HKEY_USERS、HKEY_PERFORMANCE_DATA、HKEY_CURRENT_CONFIG 和 HKEY_DYN_DATA。Valid root names include HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_PERFORMANCE_DATA, HKEY_CURRENT_CONFIG, and HKEY_DYN_DATA.

备注

SetValue 方法打开一个注册表项,设置值,并在每次调用时关闭该密钥。The SetValue method opens a registry key, sets the value, and closes the key each time it is called. 如果需要修改大量值,RegistryKey.SetValue 方法可能提供更好的性能。If you need to modify a large number of values, the RegistryKey.SetValue method might provide better performance. RegistryKey 类还提供了一些方法,使你可以将访问控制列表(ACL)添加到注册表项,以便在检索值之前测试值的数据类型以及删除键。The RegistryKey class also provides methods that allow you to add an access control list (ACL) to a registry key, to test the data type of a value before retrieving it, and to delete keys.

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

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

此重载等效于调用 RegistryValueKind.UnknownSetValue(String, String, Object, RegistryValueKind) 方法重载。This overload is equivalent to calling the SetValue(String, String, Object, RegistryValueKind) method overload with RegistryValueKind.Unknown.

备注

在 Windows 98 和 Windows Millennium Edition (Windows Me)上,注册表不是 Unicode,并且并非所有 Unicode 字符对于所有代码页都有效。On Windows 98 and Windows Millennium Edition (Windows Me), 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

SetValue(String, String, Object, RegistryValueKind)

通过使用指定的注册表数据类型,设置该指定的注册表项的名称/值对。Sets the name/value pair on the specified registry key, using the specified registry data type. 如果指定的项不存在,则创建该项。If the specified key does not exist, it is created.

public:
 static void SetValue(System::String ^ keyName, System::String ^ valueName, System::Object ^ value, Microsoft::Win32::RegistryValueKind valueKind);
public static void SetValue (string keyName, string valueName, object value, Microsoft.Win32.RegistryValueKind valueKind);
static member SetValue : string * string * obj * Microsoft.Win32.RegistryValueKind -> unit
Public Shared Sub SetValue (keyName As String, valueName As String, value As Object, valueKind As RegistryValueKind)

参数

keyName
String

以有效注册表根(如“HKEY_CURRENT_USER”)开头的键的完整注册表路径。The full registry path of the key, beginning with a valid registry root, such as "HKEY_CURRENT_USER".

valueName
String

名称/值对的名称。The name of the name/value pair.

value
Object

要存储的值。The value to be stored.

valueKind
RegistryValueKind

在存储数据时要使用的注册表数据类型。The registry data type to use when storing the data.

异常

valuenullvalue is null.

keyName 未以有效注册表根开头。keyName does not begin with a valid registry root.

- 或 --or- keyName 的长度超过了允许的最大长度(255 个字符)。keyName is longer than the maximum length allowed (255 characters).

- 或 --or- 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 is read-only, and thus cannot be written to; for example, it is a root-level node, or the key has not been opened with write access.

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

示例

下面的代码示例将多个数据类型的值存储在一个示例键中,按其创建键,然后检索并显示这些值。The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. 该示例演示了在名称/值对不存在时,存储和检索默认(无名称)名称/值对,并使用 defaultValueThe example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.

using namespace System;
using namespace Microsoft::Win32;

int main()
{   
    // The name of the key must include a valid root.
    String^ userRoot = "HKEY_CURRENT_USER";
    String^ subKey = "RegistrySetValueExample2";
    String^ keyName = String::Concat(userRoot, "\\", subKey);
    
    // An int value can be stored without specifying the
    // registry data type, but Int64 values will be stored
    // as strings unless you specify the type. Note that
    // the int is stored in the default name/value
    // pair.
    Registry::SetValue(keyName, "", 5280);
    Registry::SetValue(keyName, "TestInt64", 12345678901234, 
        RegistryValueKind::QWord);
    
    // Strings with expandable environment variables are
    // stored as ordinary strings unless you specify the
    // data type.
    Registry::SetValue(keyName, "TestExpand", "My path: %path%");
    Registry::SetValue(keyName, "TestExpand2", "My path: %path%", 
        RegistryValueKind::ExpandString);
    
    // Arrays of strings are stored automatically as 
    // MultiString. Similarly, arrays of Byte are stored
    // automatically as Binary.
    array<String^>^ strings  = {"One", "Two", "Three"};
    Registry::SetValue(keyName, "TestArray", strings);
    
    // Your default value is returned if the name/value pair
    // does not exist.
    String^ noSuch = (String^)Registry::GetValue(keyName, 
        "NoSuchName", 
        "Return this default if NoSuchName does not exist.");
    Console::WriteLine("\r\nNoSuchName: {0}", noSuch);
    
    // Retrieve the int and Int64 values, specifying 
    // numeric default values in case the name/value pairs
    // do not exist. The int value is retrieved from the
    // default (nameless) name/value pair for the key.
    int testInteger = (int)Registry::GetValue(keyName, "", -1);
    Console::WriteLine("(Default): {0}", testInteger);
    long long testInt64 = (long long)Registry::GetValue(keyName, 
        "TestInt64", System::Int64::MinValue);
    Console::WriteLine("TestInt64: {0}", testInt64);
    
    // When retrieving a MultiString value, you can specify
    // an array for the default return value. 
    array<String^>^ testArray = (array<String^>^)Registry::GetValue(
        keyName, "TestArray", 
        gcnew array<String^> {"Default if TestArray does not exist."});
    for (int i = 0; i < testArray->Length; i++)
    {
        Console::WriteLine("TestArray({0}): {1}", i, testArray[i]);
    }
    
    // A string with embedded environment variables is not
    // expanded if it was stored as an ordinary string.
    String^ testExpand = (String^)Registry::GetValue(keyName, 
        "TestExpand", "Default if TestExpand does not exist.");
    Console::WriteLine("TestExpand: {0}", testExpand);
    
    // A string stored as ExpandString is expanded.
    String^ testExpand2 = (String^)Registry::GetValue(keyName, 
        "TestExpand2", "Default if TestExpand2 does not exist.");
    Console::WriteLine(
        "TestExpand2: {0}...", testExpand2->Substring(0, 40));
    Console::WriteLine(
        "\r\nUse the registry editor to examine the key.");
    Console::WriteLine("Press the Enter key to delete the key.");
    Console::ReadLine();
    Registry::CurrentUser->DeleteSubKey(subKey);
}
//
// This code example produces output similar to the following:
//
// NoSuchName: Return this default if NoSuchName does not exist.
// (Default): 5280
// TestInt64: 12345678901234
// TestArray(0): One
// TestArray(1): Two
// TestArray(2): Three
// TestExpand: My path: %path%
// TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
// Use the registry editor to examine the key.
// Press the Enter key to delete the key.
using System;
using Microsoft.Win32;

public class Example
{
    public static void Main()
    {
        // The name of the key must include a valid root.
        const string userRoot = "HKEY_CURRENT_USER";
        const string subkey = "RegistrySetValueExample";
        const string keyName = userRoot + "\\" + subkey;

        // An int value can be stored without specifying the
        // registry data type, but long values will be stored
        // as strings unless you specify the type. Note that
        // the int is stored in the default name/value
        // pair.
        Registry.SetValue(keyName, "", 5280);
        Registry.SetValue(keyName, "TestLong", 12345678901234,
            RegistryValueKind.QWord);

        // Strings with expandable environment variables are
        // stored as ordinary strings unless you specify the
        // data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%");
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%",
            RegistryValueKind.ExpandString);

        // Arrays of strings are stored automatically as 
        // MultiString. Similarly, arrays of Byte are stored
        // automatically as Binary.
        string[] strings = {"One", "Two", "Three"};
        Registry.SetValue(keyName, "TestArray", strings);

        // Your default value is returned if the name/value pair
        // does not exist.
        string noSuch = (string) Registry.GetValue(keyName, 
            "NoSuchName",
            "Return this default if NoSuchName does not exist.");
        Console.WriteLine("\r\nNoSuchName: {0}", noSuch);

        // Retrieve the int and long values, specifying 
        // numeric default values in case the name/value pairs
        // do not exist. The int value is retrieved from the
        // default (nameless) name/value pair for the key.
        int tInteger = (int) Registry.GetValue(keyName, "", -1);
        Console.WriteLine("(Default): {0}", tInteger);
        long tLong = (long) Registry.GetValue(keyName, "TestLong",
            long.MinValue);
        Console.WriteLine("TestLong: {0}", tLong);

        // When retrieving a MultiString value, you can specify
        // an array for the default return value. 
        string[] tArray = (string[]) Registry.GetValue(keyName,
            "TestArray",
            new string[] {"Default if TestArray does not exist."});
        for(int i=0; i<tArray.Length; i++)
        {
            Console.WriteLine("TestArray({0}): {1}", i, tArray[i]);
        }

        // A string with embedded environment variables is not
        // expanded if it was stored as an ordinary string.
        string tExpand = (string) Registry.GetValue(keyName,
             "TestExpand", 
             "Default if TestExpand does not exist.");
        Console.WriteLine("TestExpand: {0}", tExpand);

        // A string stored as ExpandString is expanded.
        string tExpand2 = (string) Registry.GetValue(keyName,
            "TestExpand2",
            "Default if TestExpand2 does not exist.");
        Console.WriteLine("TestExpand2: {0}...",
            tExpand2.Substring(0, 40));

        Console.WriteLine("\r\nUse the registry editor to examine the key.");
        Console.WriteLine("Press the Enter key to delete the key.");
        Console.ReadLine();
        Registry.CurrentUser.DeleteSubKey(subkey);
    }
}
//
// This code example produces output similar to the following:
//
//NoSuchName: Return this default if NoSuchName does not exist.
//(Default): 5280
//TestLong: 12345678901234
//TestArray(0): One
//TestArray(1): Two
//TestArray(2): Three
//TestExpand: My path: %path%
//TestExpand2: My path: D:\Program Files\Microsoft.NET\...
//
//Use the registry editor to examine the key.
//Press the Enter key to delete the key.
Imports Microsoft.Win32

Public Class Example
    Public Shared Sub Main()
        ' The name of the key must include a valid root.
        Const userRoot As String = "HKEY_CURRENT_USER"
        Const subkey As String = "RegistrySetValueExample"
        Const keyName As String = userRoot & "\" & subkey

        ' Integer values can be stored without specifying the
        ' registry data type, but Long values will be stored
        ' as strings unless you specify the type. Note that
        ' the integer is stored in the default name/value
        ' pair.
        Registry.SetValue(keyName, "", 5280)
        Registry.SetValue(keyName, "TestLong", 12345678901234, _
            RegistryValueKind.QWord)

        ' Strings with expandable environment variables are
        ' stored as ordinary strings unless you specify the
        ' data type.
        Registry.SetValue(keyName, "TestExpand", "My path: %path%")
        Registry.SetValue(keyName, "TestExpand2", "My path: %path%", _
            RegistryValueKind.ExpandString)

        ' Arrays of strings are stored automatically as 
        ' MultiString. Similarly, arrays of Byte are stored
        ' automatically as Binary.
        Dim strings() As String = {"One", "Two", "Three"}
        Registry.SetValue(keyName, "TestArray", strings)

        ' Your default value is returned if the name/value pair
        ' does not exist.
        Dim noSuch As String = _
            Registry.GetValue(keyName, "NoSuchName", _
            "Return this default if NoSuchName does not exist.")
        Console.WriteLine(vbCrLf & "NoSuchName: {0}", noSuch)

        ' Retrieve the Integer and Long values, specifying 
        ' numeric default values in case the name/value pairs
        ' do not exist. The Integer value is retrieved from the
        ' default (nameless) name/value pair for the key.
        Dim tInteger As Integer = _
            Registry.GetValue(keyName, "", -1)
        Console.WriteLine("(Default): {0}", tInteger)
        Dim tLong As Long = Registry.GetValue(keyName, _
             "TestLong", Long.MinValue)
        Console.WriteLine("TestLong: {0}", tLong)

        ' When retrieving a MultiString value, you can specify
        ' an array for the default return value. The value is
        ' declared inline, but could also be declared as:
        ' Dim default() As String = {"Default value."}
        '
        Dim tArray() As String = _
            Registry.GetValue(keyName, "TestArray", _
            New String() {"Default if TestArray does not exist."})
        For i As Integer = 0 To tArray.Length - 1
            Console.WriteLine("TestArray({0}): {1}", i, tArray(i))
        Next

        ' A string with embedded environment variables is not
        ' expanded if it was stored as an ordinary string.
        Dim tExpand As String = Registry.GetValue(keyName, _
             "TestExpand", "Default if TestExpand does not exist.")
        Console.WriteLine("TestExpand: {0}", tExpand)

        ' A string stored as ExpandString is expanded.
        Dim tExpand2 As String = Registry.GetValue(keyName, _
             "TestExpand2", "Default if TestExpand2 does not exist.")
        Console.WriteLine("TestExpand2: {0}...", _
            tExpand2.Substring(0, 40))

        Console.WriteLine(vbCrLf & _
            "Use the registry editor to examine the key.")
        Console.WriteLine("Press the Enter key to delete the key.")
        Console.ReadLine()
        Registry.CurrentUser.DeleteSubKey(subkey)
    End Sub
End Class
'
' This code example produces output similar to the following:
'
'NoSuchName: Return this default if NoSuchName does not exist.
'(Default): 5280
'TestLong: 12345678901234
'TestArray(0): One
'TestArray(1): Two
'TestArray(2): Three
'TestExpand: My path: %path%
'TestExpand2: My path: D:\Program Files\Microsoft.NET\...
'
'Use the registry editor to examine the key.
'Press the Enter key to delete the key.

注解

.NET Framework 4.NET Framework 4开始,valueName 参数不再限制在最多255个字符之间;但 keyName 参数继续具有255字符的限制。Starting with the .NET Framework 4.NET Framework 4, the valueName parameter is no longer restricted to a maximum of 255 characters; however, the keyName parameter continues have the 255-character restriction.

由于注册表中的每个键都可以存储许多值,因此必须使用 valueName 参数来指定要设置的特定值。Because many values can be stored in each key in the registry, you must use the valueName parameter to specify the particular value you want to set.

备注

注册表项可以包含一个不与任何名称关联的值。A registry key can contain 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. 若要设置此未命名值,请为 valueName指定 null 或空字符串("")。To set this unnamed value, specify either null or the empty string ("") for valueName.

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

如果 keyName 指定的子项不存在,则会在指定的根中创建该子项。If keyName specifies a subkey that does not exist, the subkey is created in the specified root. 例如,在 Visual Basic 字符串 "HKEY_CURRENT_USER \MyTestKey" 在 HKEY_CURRENT_USER 根中创建子项 "MyTestKey"。For example, in Visual Basic the string "HKEY_CURRENT_USER\MyTestKey" creates the subkey "MyTestKey" in the HKEY_CURRENT_USER root. 字符串 "HKEY_CURRENT_USER \MyTestKey\Key2\Key3" 创建嵌套子项 "MyTestKey"、"MyTestKey\Key2" 和 "MyTestKey\Key2\Key3"。The string "HKEY_CURRENT_USER\MyTestKey\Key2\Key3" creates the nested subkeys "MyTestKey", "MyTestKey\Key2", and "MyTestKey\Key2\Key3".

有效的根名称包括 HKEY_CURRENT_USER、HKEY_LOCAL_MACHINE、HKEY_CLASSES_ROOT、HKEY_USERS、HKEY_PERFORMANCE_DATA、HKEY_CURRENT_CONFIG 和 HKEY_DYN_DATA。Valid root names include HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_PERFORMANCE_DATA, HKEY_CURRENT_CONFIG, and HKEY_DYN_DATA.

备注

SetValue 方法打开一个注册表项,设置值,并在每次调用时关闭该密钥。The SetValue method opens a registry key, sets the value, and closes the key each time it is called. 如果需要修改大量值,RegistryKey.SetValue 方法可能提供更好的性能。If you need to modify a large number of values, the RegistryKey.SetValue method might provide better performance. RegistryKey 类还提供了一些方法,使你可以将访问控制列表(ACL)添加到注册表项,以便在检索值之前测试值的数据类型以及删除键。The RegistryKey class also provides methods that allow you to add an access control list (ACL) to a registry key, to test the data type of a value before retrieving it, and to delete keys.

如果指定 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.

备注

在 Windows 98 和 Windows Millennium Edition (Windows Me)上,注册表不是 Unicode,并且并非所有 Unicode 字符对于所有代码页都有效。On Windows 98 and Windows Millennium Edition (Windows Me), 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

适用于