Bart Friederichs Bart Friederichs - 3 months ago 82
C# Question

Getting Windows serial number (was: Getting MachineGuid from Registry)

I am trying to fetch

MachineGuid
from the registry, to create some level of binding with the OS for my license system. From the documentation I can use

string key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography";
string r = (string)Registry.GetValue(key, "MachineGuid", (object)"default");


to get it. Also, the docs tell me that I get
"default"
when the name is not found, or
null
if the key doesn't exist. I should get a security exception if I have no access.

The above code gives me
"default"
, which means the name isn't found. However, if I look in the registry with RegEdit, it's there. How do I get the
MachineGuid
value from an application without administrator privileges?

Update: when using
reg.exe
I have no problems getting the value.

Update: I updated the title, so people looking for a unique way of determining the Windows install get here as well.

Answer

As other people have already pointed out, you are not supposed to get that value directly from the registry (which is probably why it doesn't work reliably among different versions of Windows).

A little searching led me to the Win32_OperatingSystem WMI class. Using this class, you can actually get the Windows serial number. It took me some searching and experimenting to get it right, but this is how to use it in C#.

Make sure you have the System.Management.dll reference in your project:

using System.Management;

...

ManagementObject os = new ManagementObject("Win32_OperatingSystem=@");
string serial = (string)os["SerialNumber"];

Using the [] operator, you can get any property in the class.