As a follow-up on my post from yesterday about generating shorter GUIDs, I’ve created a small helper class in C#. The class encodes a GUID into a 22 character long string and decodes the string back to the original GUID again.

That way you can save 10 characters from the original GUID and it is ASCII encoded so it will work perfectly in a URL as a query string or in ViewState.

It takes a standard GUID like this:


And converts it into this smaller string:


using System;

public static class GuidEncoder
 public static string Encode(string guidText)
  Guid guid = new Guid(guidText);
  return Encode(guid);

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

 public static Guid Decode(string encoded)
  encoded = encoded.Replace("_", "/");
  encoded = encoded.Replace("-", "+");
  byte[] buffer = Convert.FromBase64String(encoded + "==");
  return new Guid(buffer);

It basically just converts a GUID into a base64 string and shortens it a bit.