如何从注册表中检索REG_BINARY值并将其转换为字符串 [英] How to retrieve a REG_BINARY value from registry and convert to string

查看:241
本文介绍了如何从注册表中检索REG_BINARY值并将其转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码对我不起作用,我也不知道为什么。 (我已经阅读了可能已经找到答案的问题中的2个匹配项,但没有帮助。)

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.)

我需要检索Windows为之创建的唯一编号注册表中的C:驱动器。该值为REG_BINARY,我需要它在字符串中。当我说代码不起作用时,我的意思是当键值为:
19 49 84 25 00 00 50 06 00 00 00 00时,它始终仅返回2个奇怪的字符,我希望使用原始键值作为字符串

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.

推荐答案


它总是只返回2个奇怪的字符

it always return only 2 strange characters

您从前4个字节中得到两个unicode字符,然后 00 00 个字节充当字符串终止符。

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

如果要输出类似 19-49-84-25-00-00-50-06-00-00-00- 00 ,那么您可以改为执行以下操作:

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

请参阅此问题, byte []转换为十六进制字符串以获取更多详细信息和选项。

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

这篇关于如何从注册表中检索REG_BINARY值并将其转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆