问题描述:

On success of a web service i receive a UUID.

ie "C3D668DC-1231-3902-49318B046AD48A5F"

I need to validate this. I've tried

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

But it doesn't parse? is there another .net method i should use.

网友答案:

Basically the format of the GUID is slightly off. The GUID(string) constructor accepts a few different formats, but not the one you've got there. You could either put in an extra hyphen or (more simply) remove them all:

Guid responseId = new Guid(id.Replace("-", ""));
网友答案:

The Guid class does not have a TryParse method but you can roll it quite simplely your self:

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

According to the doc new Guid(string g) parses the following format:

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. 
相关阅读:
Top