如何在C#中为运行Windows 8的计算机获取唯一标识符?

我正在开发一个用C#编写的Metro应用程序,需要一种唯一识别设备的方法。 我在文档中找到了ASHWID看起来很棒。 建议的代码如下:

HardwareToken token = HardwareIdentification.GetPackageSpecificToken(null); IBuffer hardwareId = token.Id; IBuffer signature = token.Signature; IBuffer certificate = token.Certificate; 

问题是,如何将IBuffer变成我可以使用的字符串?

在通过JS或C ++中的实际建议进行了大量搜索后,我终于找到了答案!

 private string GetHardwareId() { var token = HardwareIdentification.GetPackageSpecificToken(null); var hardwareId = token.Id; var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId); byte[] bytes = new byte[hardwareId.Length]; dataReader.ReadBytes(bytes); return BitConverter.ToString(bytes); } 

谢谢你去看看这个博客 – http://bartwullems.blogspot.co.uk/2012/09/windows-8-uniquely-identifying-device.html

这应该也可以,但我没有Windows 8来测试…

 private string GetHardwareId() { return BitConverter.ToString(Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null).Id.ToArray()); } 

如果你多次调用它,你可能想把它放在Lazy

 private static Lazy _hardwareId = new Lazy(() => BitConverter.ToString(Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null).Id.ToArray()), true); public string HardwareId() { return _hardwareId.Value; } 

或者只是让它静止,如果你知道它将永远被调用:

 public static readonly string HardwareId = BitConverter.ToString(Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null).Id.ToArray())); 

您可以使用HardwareIdentification.GetPackageSpecificToken(null) ,请参阅http://msdn.microsoft.com/en-us/library/windows/apps/jj553431.aspx

该function为您提供了大量信息,您可以根据需要进行过滤。 例如:

 public static string GetMachineId() { var hardwareToken = HardwareIdentification.GetPackageSpecificToken(null).Id.ToArray(); var count = hardwareToken.Length / 4; ulong id = 0ul; for (int i = 0; i < count; i++) { switch (BitConverter.ToUInt16(hardwareToken, i * 4)) { case 1: // processor case 2: // memory case 9: // system BIOS id = (id << 12) ^ BitConverter.ToUInt16(hardwareToken, i * 4 + 2); break; } } return Convert.ToBase64String(BitConverter.GetBytes(id)); } 

但是,请记住,此function和底层API无法保证连接到互联网的所有计算机的绝对唯一性。 您通常会将此与有关用户的信息结合起来。

另一种选择是在本地(非漫游)存储中生成和存储GUID,并将其用作您的计算机ID。 根据您的具体需求,这可能是更好的解决方案。

对于guid id,您可以执行以下操作作为上述答案的扩展

  private Guid GetHardwareId() { var token = HardwareIdentification.GetPackageSpecificToken(null); var hardwareId = token.Id; var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId); byte[] bytes = new byte[hardwareId.Length]; dataReader.ReadBytes(bytes); byte[] deviceId = new byte[16]; Array.Copy((byte[])bytes, deviceId, deviceId.Length); return new Guid(deviceId); }