Reputation: 21561
So, I have a valid GUID string below
Guid.Parse("e6f85ae0-f479-4e98-9287-98f7e62ba083") // Parses just fine
This parses to a GUID in .NET4.0 / 4.5
However this code
// Copy paste this line in VS Immediate window. Does not parse!!
Guid.Parse("e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083")
Does not parse. The Guid strings are identical, or so I thought. Try it, in the immediate window of Visual Studio, the first does not parse, but second one does!
You can also verify with this code
var string1 = "e6f85ae0-f479-4e98-9287-98f7e62ba083";
var string2 = "e6f85ae0‐f479‐4e98‐9287‐98f7e62ba083";
bool isSame = string1.Equals(string2); // Equals false!! :/
Could this be an encoding issue? Is there any way to detect this issue and correctly parse the GUID?
Upvotes: 0
Views: 2801
Reputation: 3558
As decPL already said the the strings are not identical due to different hyphens used, So Guid.Parse will definitely fail. To detect that the GUID is computer readable you can use Guid.TryParse Method.
bool isValidGUID = Guid.TryParse(string2, null);
And there is nothing called human readable If you are going to replace 'narrow hyphen' then in case it contains some other symbol your code will fail. Instead of using workaround I suggest you the debug the cause for getting the 'narrow hyphen'
GUID also supports various formats. If you want to validate a specified format then you can use Guid.TryParseExact Method.
Upvotes: 1
Reputation: 5402
I'm half convinced this is a trolling question, but in case it is an honest problem:
Those strings are not identical. the second one uses the so called 'narrow hyphen' ('\u2010'
), which is a completely different character than the regular hyphen ('\u002D'
) and as such it is not parsed correctly.
Upvotes: 2