Dagoosh!

Randomsauce

Guid.TryParse Solution in C#

Posted Tue, Jul 7, 2009

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.

Tagged asp.net guid.tryparse guid

More from Dagoosh!
Shakira

Midway's The GRID: What You Get

Ode to the McGriddle

Pears Before Twitter

Google: Press Enter to Search

© 1999 - 2024 Dagoosh! LLC