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
RegistryKeyclass andRegistryViewenum to access the x64 registry.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 theKEY_WOW64_32KEYflag) to access the x64 registry.BEGIN EDIT
I’ve just found an interesting post explaining why the DigitialProductId key could be null/empty:
slmgr –cpkyEND EDIT