I've used the following query to fetch hard disk serial number.
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
It returns different serial number for admin user and non-admin user as follows:
admin - WD-WCAYUS426947 non-admin - 2020202057202d44435759415355323439363734
When tried to put the non-admin serial into hex to char converter it gave W -DCWYASU249674, which is actually a character swap on every 2 characters.
Any idea to fetch the correct serial without manupulating the un-hexed format please?
As posted in the comments: This seems to be an unsolved bug in Windows, although Microsoft knows about it.
The way to solve it is to convert the hex string and swap the numbers, I wrote a method that does this for you, feel free to edit it to your needs:
public static string ConvertAndSwapHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
int j = i;
if (j != 0)
{
j = (j % 2 == 1 ? j-1 : j+1);
}
raw[j] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return System.Text.Encoding.UTF8.GetString(raw).Trim(' ', '\t', '\0');
}
Thank you very much @thedutchman, for writing the code to convert and swap the jixed characters. I combined your code and code in this link and created a new function like below:
public static string ConvertAndSwapHex(string hexString)
{
var charString = new StringBuilder();
for (var i = 0; i < hexString.Length; i += 4)
{
charString.Append(Convert.ToChar(Convert.ToUInt32(hexString.Substring(i + 2, 2), 16)));
charString.Append(Convert.ToChar(Convert.ToUInt32(hexString.Substring(i, 2), 16)));
}
return charString.ToString();
}
One more important thing is, as mentioned in this microsoft forum, using Win32_DiskDrive instead of Win32_PhysicalMedia returns jinxed serial number consistently in Win 7 for both admin and non-admin users. Even though it returns completely different things in WinXP (which we don't support for our software anymore), consistently returning the jinxed serial number is good enough for me. You know I don't have to check the length of the serial number to determine if I need to use the above ConvertAndSwap method or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With