YouTube-like GUID

后端 未结 8 1803
灰色年华
灰色年华 2020-12-07 16:17

Is it possible to generate short GUID like in YouTube (N7Et6c9nL9w)?

How can it be done? I want to use it in web app.

8条回答
  •  醉梦人生
    2020-12-07 16:54

    As mentioned in the accepted answer, it can cause problems if you're using the GUID in the URL. Here is a more complete answer:

        public string ToShortString(Guid guid)
        {
            var base64Guid = Convert.ToBase64String(guid.ToByteArray());
    
            // Replace URL unfriendly characters with better ones
            base64Guid = base64Guid.Replace('+', '-').Replace('/', '_');
    
            // Remove the trailing ==
            return base64Guid.Substring(0, base64Guid.Length - 2);
        }
    
        public Guid FromShortString(string str)
        {
            str = str.Replace('_', '/').Replace('-', '+');
            var byteArray = Convert.FromBase64String(str + "==");
            return new Guid(byteArray);
        }
    

    Usage:

            var guid = Guid.NewGuid();
            var shortStr = ToShortString(guid);
            // shortStr will look something like 2LP8GcHr-EC4D__QTizUWw
            var guid2 = FromShortString(shortStr);
            Assert.AreEqual(guid, guid2);
    

提交回复
热议问题