如何在Windows 8中将硬件ID作为GUID格式

时间:2013-02-20 01:47:42

标签: windows-8 guid

我正在开发一个Windows应用商店应用(a.k.a metro app)。我需要将机器ID作为GUID格式。

我有这段代码:

var token = HardwareIdentification.GetPackageSpecificToken(null);
var hardwareId = token.Id;
byte[] bytes = new byte[hardwareId.Length];
dataReader.ReadBytes(bytes);
String machineId = BitConverter.ToString(bytes);

machineId是一个字符串,但它与GUID不匹配。有人知道如何以GUID格式转换这个值吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码。它基于另一个SO thread的代码。

    private async void  Button_Click_1(object sender, RoutedEventArgs e)
    {
        //dataReader.ReadBytes(bytes);
        String machineId = BitConverter.ToString(bytes);


        Guid guid;

        bool isDataAVailale = GuidTryParse(machineId, out guid);

        myText.Text = guid.ToString();

    }


    public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Singleline);