如何在C#中解析UUID

时间:2010-04-03 13:43:19

标签: c#

Web服务成功后,我会收到UUID。

即“C3D668DC-1231-3902-49318B046AD48A5F”

我需要验证这一点。我试过了

Guid responseId = new Guid(“C3D668DC-1231-3902-49318B046AD48A5F”);

但它没有解析?是否有我应该使用的另一种.net方法。

2 个答案:

答案 0 :(得分:9)

基本上GUID的格式略有偏差。 GUID(字符串)构造函数接受几种不同的格式,但不是您所拥有的格式。您可以添加一个额外的连字符或(更简单地)将它们全部删除:

Guid responseId = new Guid(id.Replace("-", ""));

答案 1 :(得分:3)

Guid类没有TryParse方法,但您可以非常简单地推广它自己:

public bool TryParseGuid(string value, out Guid result) {
    try {
        result = new Guid(value.Replace("-", ""); // needed to cater for wron hyphenation
        return true;
    } catch {
        result = Guid.Empty;
        return false;
    }
}

根据doc新Guid(字符串g)解析以下格式:

A String  that contains a GUID in one of the following formats ('d' represents a hexadecimal digit whose case is ignored):
32 contiguous digits:
dddddddddddddddddddddddddddddddd
-or-
Groups of 8, 4, 4, 4, and 12 digits with hyphens between the groups. The entire GUID can optionally be enclosed in matching braces or parentheses:
dddddddd-dddd-dddd-dddd-dddddddddddd
-or-
{dddddddd-dddd-dddd-dddd-dddddddddddd}
-or-
(dddddddd-dddd-dddd-dddd-dddddddddddd)
-or-
Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits, with each group prefixed by "0x" or "0X", and separated by commas. The entire GUID, as well as the subset, is enclosed in matching braces:
{0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
All braces, commas, and "0x" prefixes are required. All embedded spaces are ignored. All leading zeroes in a group are ignored.
The digits shown in a group are the maximum number of meaningful digits that can appear in that group. You can specify from 1 to the number of digits shown for a group. The specified digits are assumed to be the low order digits of the group.