Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

limiting the number of character in GUID

Tags:

guid

c#-4.0

is it possible or is there any overload to get a less than 32 characters of GUID ? currently i am using this statement but its giving me error

string guid = new Guid("{dddd-dddd-dddd-dddd}").ToString();

i want a key of 20 characters

like image 658
vakas Avatar asked Jan 12 '12 14:01

vakas


1 Answers

You can use a ShortGuid. Here is an example of an implementation.

It's nice to use ShortGuids in URLs or other places visible to an end user.

The following code:

Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine( sguid1 );
Console.WriteLine( sguid1.Guid );

Will give you this output:

FEx1sZbSD0ugmgMAF_RGHw
b1754c14-d296-4b0f-a09a-030017f4461f

This is the code for an Encode and Decode method:

public static string Encode(Guid guid)
{
   string encoded = Convert.ToBase64String(guid.ToByteArray());
   encoded = encoded
     .Replace("/", "_")
     .Replace("+", "-");
   return encoded.Substring(0, 22);
}

public static Guid Decode(string value)
{
   value = value
     .Replace("_", "/")
     .Replace("-", "+");
   byte[] buffer = Convert.FromBase64String(value + "==");
   return new Guid(buffer);
}
like image 121
Wouter de Kort Avatar answered Sep 19 '22 20:09

Wouter de Kort