Ben Junior
Ben Junior

Reputation: 2589

How to retrieve a REG_BINARY value from registry and convert to string

The code below is not working for me and I don't know why. (I have read the 2 match in "Questions that may already have your answer" but didn't help.)

I need to retrieve the unique number that Windows create for the C: drive in the registry. The value is REG_BINARY and I need it in string. When I said that the code doesn't work I meant it always return only 2 strange characters when the key value is: 19 49 84 25 00 00 50 06 00 00 00 00 I would prefer to have the original key value as a string

byte[] machineID = (byte[])Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\SYSTEM\\MountedDevices", "\\DosDevices\\C:", null);
if (machineID != null)
  {
    var str = System.Text.Encoding.Default.GetString(machineID);
    MessageBox.Show(str);
  }

Note: I know that this value may change if the drive is reformatted or the OS is re installed but this is OK for me as long as it is tied to this specific machine.

Upvotes: 0

Views: 6229

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103467

You are trying to interpret something that is not a string as a string.

it always return only 2 strange characters

You're getting two unicode characters from the first 4 bytes, then the 00 00 bytes are acting as a string terminator.

If you want output like "19-49-84-25-00-00-50-06-00-00-00-00", then you can do this instead:

var str = BitConverter.ToString(machineID);

See this question, "byte[] to hex string" for more details and options.

Upvotes: 2

Related Questions