Generate GUID from any string using C#

Posted by Haitham Khedre on ASP.net Weblogs See other posts from ASP.net Weblogs or by Haitham Khedre
Published on Fri, 11 Mar 2011 23:47:44 GMT Indexed on 2011/03/12 0:11 UTC
Read the original article Hit count: 131

Filed under:

Some times you need to generate GUID from a string which is not valid for GUID constructor .

so what we will do is to get a valid input from string that the GUID constructor will accept it.

It is recommended to be sure that the string that you will generate a GUID from it some how unique.

The Idea is simple is to convert the string to 16 byte Array which the GUID constructor will accept it.

The code will talk :

using System;
using System.Text;


namespace StringToGUID
{
    class Program
    {
        static void Main(string[] args)
        {
            int tokenLength = 32;
            int guidByteSize = 16;
            string token = "BSNAItOawkSl07t77RKnMjYwYyG4bCt0g8DVDBv5m0";
            byte[] b = new UTF8Encoding().GetBytes(token.Substring(token.Length - tokenLength, tokenLength).ToCharArray(), 0, guidByteSize);
            Guid g = new Guid(b);
            Console.WriteLine(g.ToString());
            token = "BSNePf57YwhzeE9QfOyepPfIPao4UD5UohG_fI-#eda7d";
            b = new UTF8Encoding().GetBytes(token.Substring(token.Length - tokenLength, tokenLength).ToCharArray(), 0, guidByteSize);
            g = new Guid(b);
            Console.WriteLine(g.ToString());
            Console.Read();
        }
    }
}

 

And The output:

37306c53-3774-5237-4b6e-4d6a59775979

66513945-794f-7065-5066-4950616f3455

© ASP.net Weblogs or respective owner

Related posts about c#