Home > c#, Code > How to read computer SID on 64-bit machine

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

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

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.

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

Cheers
John

VN:F [1.9.22_1171]
Rating: 5.5/10 (2 votes cast)
How to read computer SID on 64-bit machine, 5.5 out of 10 based on 2 ratings
Categories: c#, Code Tags:
  1. Jim
    January 7th, 2016 at 03:48 | #1

    Not the SID. Product ID is not the SID of the machine account.

    VA:F [1.9.22_1171]
    Rating: +2 (from 2 votes)
  1. No trackbacks yet.