guid to base64, for URL

前端 未结 4 731
不知归路
不知归路 2020-12-04 19:20

Question: is there a better way to do that?

VB.Net

Function GuidToBase64(ByVal guid As Guid) As String
    Return Convert.ToBase64String(guid.ToByteA         


        
4条回答
  •  鱼传尺愫
    2020-12-04 19:40

    You might want to check out this site: http://prettycode.org/2009/11/12/short-guid/

    It looks very close to what you're doing.

    public class ShortGuid
    {
        private readonly Guid guid;
        private readonly string value;
    
        /// Create a 22-character case-sensitive short GUID.
        public ShortGuid(Guid guid)
        {
            if (guid == null)
            {
                throw new ArgumentNullException("guid");
            }
    
            this.guid = guid;
            this.value = Convert.ToBase64String(guid.ToByteArray())
                .Substring(0, 22)
                .Replace("/", "_")
                .Replace("+", "-");
        }
    
        /// Get the short GUID as a string.
        public override string ToString()
        {
            return this.value;
        }
    
        /// Get the Guid object from which the short GUID was created.
        public Guid ToGuid()
        {
            return this.guid;
        }
    
        /// Get a short GUID as a Guid object.
        /// 
        /// 
        public static ShortGuid Parse(string shortGuid)
        {
            if (shortGuid == null)
            {
                throw new ArgumentNullException("shortGuid");
            }
            else if (shortGuid.Length != 22)
            {
                throw new FormatException("Input string was not in a correct format.");
            }
    
            return new ShortGuid(new Guid(Convert.FromBase64String
                (shortGuid.Replace("_", "/").Replace("-", "+") + "==")));
        }
    
        public static implicit operator String(ShortGuid guid)
        {
            return guid.ToString();
        }
    
        public static implicit operator Guid(ShortGuid shortGuid)
        {
            return shortGuid.guid;
        }
    }
    

提交回复
热议问题