Read and Write Registry Keys and Values in C#

The Registry and RegistryKey classes in the Microsoft.Win32 namespace read and write the Windows registry. They are built into .NET, no package needed, but they only work on Windows. Target net8.0-windows so the compiler knows that and doesn’t flag every call with a platform warning (CA1416):

<PropertyGroup>
  <TargetFramework>net8.0-windows</TargetFramework>
</PropertyGroup>

A WinForms app has <UseWindowsForms>true</UseWindowsForms> in the same group; the registry code does not depend on it.

Write and read values

using Microsoft.Win32;

const string KeyPath = @"Software\CSharpExamples\DemoApp";

using (RegistryKey key = Registry.CurrentUser.CreateSubKey(KeyPath))
{
    key.SetValue("Homepage", "https://www.csharpexamples.com");
    key.SetValue("LaunchCount", 123);
}

using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(KeyPath))
{
    string homepage = key?.GetValue("Homepage") as string ?? "(not set)";
    int launchCount = key?.GetValue("LaunchCount") is int n ? n : 0;

    Console.WriteLine($"{homepage}, launched {launchCount} times");
}
// https://www.csharpexamples.com, launched 123 times

CreateSubKey opens the key for writing and creates any missing keys along the path, so it is safe to call every time. OpenSubKey returns null when the key does not exist and opens it read-only unless you pass writable: true. GetValue returns null for a missing value, or you can pass a default: key.GetValue("LaunchCount", 0).

RegistryKey holds a native handle. Dispose it, with using as above, or you leak handles in long-running processes.

Value types

SetValue(name, object) picks the registry type from the .NET type:

.NET typeRegistry type
intREG_DWORD
stringREG_SZ
string[]REG_MULTI_SZ
byte[]REG_BINARY
any other non-array type, including longREG_SZ via ToString()

Other array types throw an ArgumentException. The last row is the real trap: a long ends up stored as text. Pass the kind explicitly when you need a 64-bit number:

key.SetValue("LastRunTicks", DateTime.UtcNow.Ticks, RegistryValueKind.QWord);

GetValue also expands environment variables in REG_EXPAND_SZ values, so %USERPROFILE%\Documents comes back as a full path. To get the raw text, pass RegistryValueOptions.DoNotExpandEnvironmentNames.

Delete values and keys

using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(KeyPath, writable: true))
{
    key?.DeleteValue("LaunchCount", throwOnMissingValue: false);
}

Registry.CurrentUser.DeleteSubKeyTree(KeyPath, throwOnMissingSubKey: false);

DeleteSubKey only removes a key with no subkeys; DeleteSubKeyTree removes the key and everything under it, so double-check the path before calling it.

HKEY_LOCAL_MACHINE and the 32/64-bit split

Keys under HKEY_CURRENT_USER are writable by the user. HKEY_LOCAL_MACHINE is machine-wide and mostly readable by anyone, but writing to it needs administrator rights; without elevation you get an UnauthorizedAccessException. Most applications should not write there outside their installer.

On 64-bit Windows, a 32-bit process that opens HKLM\SOFTWARE is silently redirected to HKLM\SOFTWARE\WOW6432Node. If you read a value another program wrote and get null, this is the first thing to check. Choose the view explicitly:

using RegistryKey baseKey = RegistryKey.OpenBaseKey(
    RegistryHive.LocalMachine, RegistryView.Registry64);

using RegistryKey? key = baseKey.OpenSubKey(
    @"SOFTWARE\Microsoft\Windows NT\CurrentVersion");

Console.WriteLine(key?.GetValue("ProductName"));

Should you store settings in the registry?

For your own app’s settings, usually not. A JSON file under Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) is easier to inspect, back up, delete and move between machines, and it works on every OS .NET runs on. Use the registry when you need to integrate with Windows or other software that expects it: file associations, autostart entries under Software\Microsoft\Windows\CurrentVersion\Run, or reading configuration written by another product.

Related examples

1 thought on “Read and Write Registry Keys and Values in C#”

Leave a Comment