Often it is useful to check whether or not a string is actually a Guid, especially useful if you pass guid querystrings between pages to identify things like users, videos or blogs etc.

One way you could do this is to user a try catch around a new Guid(String) statement but its bad practice to use a try catch for this purpose. The way I like to check that a string is actually a guid is by using a regular expression. The following code is a helper method that uses this regular expression from RegexLib to test for a Guid:


Boolean IsGuid(string expression)
{
if (expression != null)
{
Regex guidRegEx = new Regex(@"[({]?(0x)?[0-9a-fA-F]{8}([-,]?(0x)?[0-9a-fA-F]{4}){2}((-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})|(,\{0x[0-9a-fA-F]{2}(,0x[0-9a-fA-F]{2}){7}\}))[)}]?");
return guidRegEx.IsMatch(expression);
}
return false;
}

I use this method in one of two place:

  • In a class that inherits from System.Web.UI.Page. All pages in my application then inherit from this class.
  • As a static method in a common class. This means that this IsGuid method can be called from anywhere without the need for an object declaration.

This method could be easily modified to check for other datatypes, not just Guids, for example integers or email addresses.

 

One Response to ASP.NET C#: Test whether a string is a GUID

  1. amit says:

    Use Guid.TryParse is another Option and Short Way to resolve the Issue

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

2,918 Spam Comments Blocked so far by Spam Free Wordpress

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>