Guid.TryParse Solution in C#

Some of my applications make heavy use of the globally unique identifier (GUID).  I always use them for user and session IDs as they are pretty hard to guess. I mean 32 hex digits (128 bits) puts you around 1632 (2128) which rounds off to somewhere between ridiculous and absurd.

 

Processing cookies and other input that may contain a GUID makes a Guid.TryParse function necessary.  Recently I found a little function I wrote a few years ago to process cookies for session IDs in an application that essentially did this:

 

Guid xie = new Guid( cookiedata );

 

Which is fine and dandy until cookiedata contained broken input due to an expired session, broken cookies or what have you.  My soultion then was just to put these statements in to try {} catch {} blocks and ignore the exception.  Today while going though the app I decided to create TryParse function for the GUID.

 

public static bool GuidTryParse(string x, out Guid g )

{

    g = Guid.Empty;

 

    if (String.IsNullOrEmpty( x ))

        return false;

 

    x = x.Replace( “-“,“” ).Replace( “{“, “”).Replace( “}”, “” );

 

    Regex r = new Regex(“[0-9A-Fa-f]{32}” );

 

    if(!r.IsMatch( x ))

        return false;

 

    g = new Guid( x );

    return true;

}

 

I am no effiency superstar, the string.replace may be (likely is) slower than writing a regex to account for all possible cases.

19 comments » Write a comment

  1. The new Zune browser is surprisingly good, but not as good as the iPod’s. It works well, but isn’t as fast as Safari, and has a clunkier interface. If you occasionally plan on using the web browser that’s not an issue, but if you’re planning to browse the web alot from your PMP then the iPod’s larger screen and better browser may be important.

  2. Great website…and cool article man…thanx for the great post…keep on posting such articles… Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful.

Leave a Reply

Required fields are marked *.