Read Windows Registry values without assuming a key exists

Opening a Registry subkey can return null. Reading a value can also return null. Handle both states before converting the result.

This example reads a Windows system value without changing the Registry. Hardware descriptions vary by machine, so the output is intentionally environment-dependent.

Read one value

Requires Windows and a .NET console project. Replace Program.cs:

C#
using Microsoft.Win32;

if (!OperatingSystem.IsWindows()) {
	Console.WriteLine("This example requires Windows.");
	return;
}

using var key = Registry.LocalMachine.OpenSubKey(
	@"HARDWARE\DESCRIPTION\System\CentralProcessor\0", writable: false);
string? vendor = key?.GetValue("VendorIdentifier") as string;
Console.WriteLine(vendor ?? "Processor vendor is unavailable.");

Run dotnet run. Expect the recorded vendor string or the explicit fallback, rather than a null-reference failure.

Preserve the key's type and view

Registry values are typed. A DWORD normally arrives as an integer, not a string. Inspect its type before conversion. Do not call ToString() blindly on a missing value.

For software keys with separate 32-bit and 64-bit views, select the intended view using RegistryKey.OpenBaseKey and RegistryView. Read-only access still depends on the key's permissions. Catch UnauthorizedAccessException or SecurityException at the application boundary when access failures are expected. Request write access only for an explicit write operation.

Official references

RegistryKey.OpenSubKey Method (Microsoft.Win32)
Retrieves the specified subkey.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.opensubkey
RegistryKey.OpenSubKey

Author: Herman Schoenfeld