Registry.SetValue Metodo

Definizione

Imposta il valore di una coppia nome/valore in una chiave del Registro di sistema.

Overload

SetValue(String, String, Object)

Imposta la coppia nome/valore specificata nella chiave del Registro di sistema specificata. Se la chiave specificata non esiste, verrà creata.

SetValue(String, String, Object, RegistryValueKind)

Imposta la coppia nome/valore nella chiave specificata del Registro di sistema, utilizzando il tipo di dati del Registro di sistema specificato. Se la chiave specificata non esiste, verrà creata.

Esempio

Nell'esempio di codice seguente vengono archiviati i valori di diversi tipi di dati in una chiave di esempio, creando la chiave così come avviene e quindi recuperando e visualizzando i valori. Nell'esempio viene illustrata l'archiviazione e il recupero della coppia nome/valore predefinita (senza nome) e l'uso di defaultValue quando non esiste una coppia nome/valore.

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)

Source:
Registry.cs

Imposta la coppia nome/valore specificata nella chiave del Registro di sistema specificata. Se la chiave specificata non esiste, verrà creata.

public:
 static void SetValue(System::String ^ keyName, System::String ^ valueName, System::Object ^ value);
public static void SetValue (string keyName, string valueName, 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)

Parametri

keyName
String

Percorso completo della chiave del Registro di sistema, che inizia con una chiave di primo livello valida, ad esempio "HKEY_CURRENT_USER".

valueName
String

Nome della coppia nome/valore.

value
Object

Valore da archiviare.

Eccezioni

value è null.

keyName non inizia con una chiave di primo livello valida del Registro di sistema.

-oppure-

keyName è maggiore della lunghezza massima consentita (255 caratteri).

L'oggetto RegistryKey è di sola lettura e non può essere modificato. Si tratta, ad esempio, di un nodo di primo livello.

L'utente non dispone delle autorizzazioni richieste per la creazione o la modifica delle chiavi del Registro di sistema.

Esempio

Nell'esempio di codice seguente vengono archiviati i valori di diversi tipi di dati in una chiave di esempio, creando la chiave così come avviene e quindi recuperando e visualizzando i valori. Nell'esempio viene illustrata l'archiviazione e il recupero della coppia nome/valore predefinita (senza nome) e l'uso di defaultValue quando non esiste una coppia nome/valore.

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.

Commenti

A partire da .NET Framework 4, il valueName parametro non è più limitato a un massimo di 255 caratteri. Tuttavia, il keyName parametro continua ad avere la restrizione di 255 caratteri.

Poiché molti valori possono essere archiviati in ogni chiave del Registro di sistema, è necessario usare il valueName parametro per specificare il valore specifico da impostare.

Nota

Una chiave del Registro di sistema può contenere un valore non associato ad alcun nome. Quando questo valore senza nome viene visualizzato nell'editor del Registro di sistema, la stringa "(Default)" viene visualizzata anziché un nome. Per impostare questo valore senza nome, specificare null o la stringa vuota ("") per valueName.

Se valueName non esiste nella chiave, viene creato e il valore associato è impostato su value.

Se keyName specifica una sottochiave che non esiste, la sottochiave viene creata nella radice specificata. Ad esempio, in Visual Basic la stringa "HKEY_CURRENT_USER\MyTestKey" crea la sottochiave "MyTestKey" nella radice HKEY_CURRENT_USER. La stringa "HKEY_CURRENT_USER\MyTestKey\Key2\Key3" crea le sottochiavi annidate "MyTestKey", "MyTestKey\Key2" e "MyTestKey\Key2\Key3".

I nomi radice validi includono HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_PERFORMANCE_DATA, HKEY_CURRENT_CONFIG e HKEY_DYN_DATA.

Nota

Il SetValue metodo apre una chiave del Registro di sistema, imposta il valore e chiude la chiave ogni volta che viene chiamata. Se è necessario modificare un numero elevato di valori, il RegistryKey.SetValue metodo potrebbe offrire prestazioni migliori. La RegistryKey classe fornisce anche metodi che consentono di aggiungere un elenco di controllo di accesso (ACL) a una chiave del Registro di sistema, di testare il tipo di dati di un valore prima di recuperarlo e di eliminare le chiavi.

Questo overload di SetValue archivia interi a 64 bit come stringhe (RegistryValueKind.String). Per archiviare i numeri a 64 bit come RegistryValueKind.QWord valori, usare l'overload del SetValue(String, String, Object, RegistryValueKind) metodo .

Questo overload di archivia tutti i valori stringa come RegistryValueKind.String oggetti, anche se contengono riferimenti espandibili alle variabili di SetValue ambiente. Per salvare i valori stringa come stringhe espandibili (RegistryValueKind.ExpandString), usare l'overload del SetValue(String, String, Object, RegistryValueKind) metodo.

Questo overload equivale a chiamare l'overload del SetValue(String, String, Object, RegistryValueKind) metodo con RegistryValueKind.Unknown.

Si applica a

SetValue(String, String, Object, RegistryValueKind)

Source:
Registry.cs

Imposta la coppia nome/valore nella chiave specificata del Registro di sistema, utilizzando il tipo di dati del Registro di sistema specificato. Se la chiave specificata non esiste, verrà creata.

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);
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)

Parametri

keyName
String

Percorso completo della chiave del Registro di sistema, che inizia con una chiave di primo livello valida, ad esempio "HKEY_CURRENT_USER".

valueName
String

Nome della coppia nome/valore.

value
Object

Valore da archiviare.

valueKind
RegistryValueKind

Tipo di dati del Registro di sistema da usare per l'archiviazione dei dati.

Eccezioni

value è null.

keyName non inizia con una chiave di primo livello valida del Registro di sistema.

-oppure-

keyName è maggiore della lunghezza massima consentita (255 caratteri).

-oppure-

Il tipo di value non corrisponde al tipo di dati del Registro di sistema specificato da valueKind, pertanto non è stato possibile convertire i dati in modo corretto.

L'oggetto RegistryKey è di sola lettura e non può essere modificata. Si tratta, ad esempio di un nodo di primo livello oppure la chiave non è stata aperta con accesso in scrittura.

L'utente non dispone delle autorizzazioni richieste per la creazione o la modifica delle chiavi del Registro di sistema.

Esempio

Nell'esempio di codice seguente vengono archiviati i valori di diversi tipi di dati in una chiave di esempio, creando la chiave così come avviene e quindi recuperando e visualizzando i valori. Nell'esempio viene illustrata l'archiviazione e il recupero della coppia nome/valore predefinita (senza nome) e l'uso di defaultValue quando non esiste una coppia nome/valore.

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.

Commenti

A partire da .NET Framework 4, il valueName parametro non è più limitato a un massimo di 255 caratteri. Tuttavia, il keyName parametro continua ad avere la restrizione di 255 caratteri.

Poiché molti valori possono essere archiviati in ogni chiave del Registro di sistema, è necessario usare il valueName parametro per specificare il valore specifico da impostare.

Nota

Una chiave del Registro di sistema può contenere un valore non associato ad alcun nome. Quando questo valore senza nome viene visualizzato nell'editor del Registro di sistema, la stringa "(Default)" viene visualizzata anziché un nome. Per impostare questo valore senza nome, specificare null o la stringa vuota ("") per valueName.

Se valueName non esiste nella chiave, viene creato e il valore associato è impostato su value.

Se keyName specifica una sottochiave che non esiste, la sottochiave viene creata nella radice specificata. Ad esempio, in Visual Basic la stringa "HKEY_CURRENT_USER\MyTestKey" crea la sottochiave "MyTestKey" nella radice HKEY_CURRENT_USER. La stringa "HKEY_CURRENT_USER\MyTestKey\Key2\Key3" crea le sottochiavi annidate "MyTestKey", "MyTestKey\Key2" e "MyTestKey\Key2\Key3".

I nomi radice validi includono HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_PERFORMANCE_DATA, HKEY_CURRENT_CONFIG e HKEY_DYN_DATA.

Nota

Il SetValue metodo apre una chiave del Registro di sistema, imposta il valore e chiude la chiave ogni volta che viene chiamata. Se è necessario modificare un numero elevato di valori, il RegistryKey.SetValue metodo potrebbe offrire prestazioni migliori. La RegistryKey classe fornisce anche metodi che consentono di aggiungere un elenco di controllo di accesso (ACL) a una chiave del Registro di sistema, di testare il tipo di dati di un valore prima di recuperarlo e di eliminare le chiavi.

Se il tipo dell'oggetto specificato non corrisponde all'oggetto specificato valuevalueKinde i dati non possono essere convertiti, ArgumentException viene generata un'eccezione . Ad esempio, è possibile archiviare un System.Int64 oggetto come RegistryValueKind.DWord, ma solo se il relativo valore è minore del valore massimo di un oggetto System.Int32. Non è possibile archiviare un singolo valore stringa come .RegistryValueKind.MultiString

Nota

Se i valori boxed vengono passati per RegistryValueKind.DWord o RegistryValueKind.QWord, la conversione viene eseguita usando le impostazioni cultura invarianti.

Si applica a