Is there any way to create a short unique code like short GUID?

masoud ramezani picture masoud ramezani · Nov 14, 2011 · Viewed 28.5k times · Source

I want to create a short GUID. Is there any way to create a short unique code like short GUID? I want to create a ticket tracking number.

Answer

JKhuang picture JKhuang · Nov 14, 2011

The length of GUID is 128bits(16bytes), so if you want to create a short GUID , you have to change GUID's encoding.

For instance, you can use base64 or ASCII85.

    /// <summary>
    /// Creates a GUID which is guaranteed not to equal the empty GUID
    /// </summary>
    /// <returns>A 24 character long string</returns>
    public static string CreateGuid()
    {
        Guid guid = Guid.Empty;
        while (Guid.Empty == guid)
        {
            guid = Guid.NewGuid();
        }

        // Uses base64 encoding the guid.(Or  ASCII85 encoded)
        // But not recommend using Hex, as it is less efficient.
        return Convert.ToBase64String(guid.ToByteArray());
    }