0

我正在开发一个 Windows Store 应用程序(又名 Metro 应用程序)。我需要以 GUID 格式获取机器 ID。

我有这个代码:

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 格式吗?

4

1 回答 1

0

试试下面的代码。它基于另一个SO 线程的代码。

    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);
于 2013-02-20T05:37:48.183 回答