2010-04-03 4 views
1

웹 서비스가 성공하면 UUID가 수신됩니다.C#에서 UUID를 구문 분석하는 방법

즉 "C3D668DC-1231-3902-49318B046AD48A5F"

나는이 문제를 확인해야합니다. 시도했습니다.

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

하지만 구문 분석하지 않습니까? .net 메서드를 사용해야합니다.

답변

9

기본적으로 GUID 형식은 약간 꺼져 있습니다. GUID (string) 생성자는 몇 가지 다른 형식을 허용하지만 사용자가 가지고있는 형식은 아닙니다. 당신도 추가 하이픈에 넣어 또는 (더 간단하게) 모두를 제거 할 수 있습니다 : 여기에 도움이되지 것

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

Guid 클래스는 TryParse 방법을 가지고 있지 않지만 그것은 아주 simplely 자기 롤백 할 수 있습니다 :

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. 
다음 doc 새 GUID (문자열 g)에 따르면

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

하면 다음과 같은 형식을 구문 분석

+0

- 그냥 항상 실패, 영업 이익은 웹 서비스 ISN '에서 다시 점점 형식 때문에 .NET이 사용하는 것. –

+0

@ 존 Skeet : 네, 맞아요 ... 코드를 수정. – AxelEckenberger

+1

그 시점에서 필자는 TryParse가 특히이 경우에 필요하다는 것을 확신하지 못합니다. 웹 서비스에서 왔을 때 유효하지 않은 문자열은 꽤 심각한 오류이며 예외는 아마도 가장 적절한 응답 일 것입니다. Btw, .NET 4 *에는 Guid.TryParse가 있습니다. –

관련 문제