I've been using the below code in order to get the Windows License Key. It worked pretty well a long time. But now I discovered that it works on Windows XP (x86) but not on Windows 7 x64.
Reason: The DigitalProductID
regisitry value contains only zeroes within the range we are looking for on the 64 bit operating system. Therefore the result it BBBBB-BBBBB-BBBBB-BBBBB-BBBBB
. Why is it so and how can I fix this?
public static string LicenseCDKey
{
get
{
try
{
byte[] rpk = (byte[])Registry.LocalMachine
.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion")
.GetValue("DigitalProductId");
string serial = "";
const string possible = "BCDFGHJKMPQRTVWXY2346789";
for (int i = 0; i < 25; i++)
{
int accu = 0;
for (int a = 0; a < 15; a++)
{
accu <<= 8;
accu += rpk[66 - a];
rpk[66 - a] = (byte)(accu / 24 & 0xff);
accu %= 24;
}
serial = possible[accu] + serial;
if (i % 5 == 4 && i < 24)
{
serial = "-" + serial;
}
}
return serial;
}
catch
{
return ErrorString;
}
}
}
As user287107 pointed out x86 applications (32 bit) running on a x64 operating system are using a different registry (registry view).
In order to access the x64 registry you have a few options:
If you are using .Net Framework 4.0 you could use the RegistryKey
class and RegistryView
enum to access the x64 registry.
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
RegistryView.Registry64);
string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion";
byte[] rpk = (byte[])key.OpenSubKey(keyPath).GetValue("DigitalProductId");
If you are not using the .Net Framework 4.0 and you do not want to set your platform target to x64 you have to use Interop (RegOpenKeyEx()
Win32 API function with the KEY_WOW64_32KEY
flag) to access the x64 registry.
BEGIN EDIT
I've just found an interesting post explaining why the DigitialProductId key could be null/empty:
slmgr –cpky
END EDIT
32 bit applications use a different registry path
a 32 bit application accesses the registry path in HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion where it does not find the product key.
changing the processor type to x64 worked for me to get the real key.