How to read computer SID on 64-bit machine

To get a unique identifier for a computer the recommended key is “ProductId” that is accessible from the following registry key – HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion.

This is the value you see as “Product ID” on the properties screen of your computer.

To access this key can be a little problematic if you are attempting to read the “ProductId” sub-key on a 64-bit machine from a 32-bit application.

This is due to Registry Reflection or WOW64 as it is sometimes called.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa384235%28v=vs.85%29.aspx

In short the 64-bit OS shows 2 logical views of certain portions of the registry on WOW64, one for 32-bit and one for 64-bit. In the case of the “ProductId” key it explicitly exists in the 64-bit view so the following code will fail to find the key, as when running inside the 32-bit application it accesses the 32-bit view of the registry and fails to find the key.

The following code will return an empty string
[csharp]
public static string ComputerSID
{
get
{
string sid = string.Empty;

string SIDKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
RegistryKey key = Registry.LocalMachine.OpenSubKey(SIDKey);

object keyValue = key.GetValue("ProductId");

if (keyValue != null)
{
sid = keyValue.ToString();
}

key = null;
keyValue = null;

return sid;
}
}
[/csharp]

To make this work you have to explicitly request c# to open the 64-bit view of the registry.
The following code sample will work.

[csharp]
public static string ComputerSID
{
get
{
string sid = string.Empty;
string SIDKey = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion";

RegistryKey baseKey = null;
if (Environment.Is64BitOperatingSystem)
{
baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
}
else
{
baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);
}

RegistryKey key = baseKey.OpenSubKey(SIDKey);

object keyValue = key.GetValue("ProductId");

if (keyValue != null)
{
sid = keyValue.ToString();
}

key = null;
keyValue = null;

return sid;
}
}
[/csharp]

Cheers
John

1 thought on “How to read computer SID on 64-bit machine

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.