7

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

vakas
  • 1,799
  • 5
  • 23
  • 40

2 Answers2

5

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);
}
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
  • This is 22 characters. The question states he wants 20 characters. You need to step up from BASE64 to ASCII85 to shave those 2 off. See David's answer. – Travis Watson Dec 20 '13 at 19:47