Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to try convert a string to a Guid [duplicate]

Tags:

c#

People also ask

How do I convert a string to a GUID?

Program to convert string into guid in . Net Framework using C# Guid. Parse method. This method contains two parameters string as an input and if this method returns true then result parameter contains a valid Guid and in case false is returned result parameter will contain Guid.

Is GUID a string?

A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string.

What is the format of a GUID?

The GUID data type is a text string representing a Class identifier (ID). COM must be able to convert the string to a valid Class ID. All GUIDs must be authored in uppercase. The valid format for a GUID is {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX} where X is a hex digit (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).

How long is a GUID string?

That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.


new Guid(string)

You could also look at using a TypeConverter.


use code like this:

new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")

instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value


Guid.TryParse()

https://msdn.microsoft.com/de-de/library/system.guid.tryparse(v=vs.110).aspx

or

Guid.TryParseExact()

https://msdn.microsoft.com/de-de/library/system.guid.tryparseexact(v=vs.110).aspx

in .NET 4.0 (or 3.5?)


This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 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.Compiled);

Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.

Those are:

  • ArgumentNullException
  • FormatException
  • OverflowException

I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.