Character limit in GUID

Is this possible or is there any kind of overload to get less than 32 characters of GUID? I am currently using this operator, but it gives me an error

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

I need a 20 character key

+4
source share
2 answers

You can use ShortGuid. Here is an example implementation.

It's good to use ShortGuids in URLs or other places visible to the 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 ); 

You will get this result:

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

This is the code for the 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); } 
+3
source

Source: https://habr.com/ru/post/1390647/


All Articles