guid与Base64编码互相转换

guid的长度比较长,本文提供一种方法,将guid转为base64字符串,只有22位长度,比较好!

参考:https://blog.csdn.net/tgghfbflishuai/article/details/17039751

 /// <summary>
    /// Guid转换类
    /// </summary>
   public class GuidConvert
    {
        /// <summary>
        /// guid转为Base64编码
        /// 长度为22个字符
        /// </summary>
        /// <param name="guid"></param>
        /// <example>
        /// string guid2 = GuidToBase64String(guid1);
        /// </example>
        /// <returns></returns>
        public static string GuidToBase64String(Guid guid)
        {
            return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "_").Replace("+", "-").Substring(0, 22);
        }

        /// <summary>
        /// 将Base64编码的guid还原为guid
        /// base64编码字符不包含最后的“==”
        /// </summary>
        /// <param name="target"></param>
        /// <example>
        /// Guid guid3 = Base64StringToGuid(guid2);
        /// </example>
        /// <returns></returns>
        public static Guid Base64StringToGuid(string base64string)
        {
            Guid guid = Guid.Empty;
            if ((!string.IsNullOrEmpty(base64string)) && (base64string.Trim().Length == 22))
            {
                string encoded = string.Concat(base64string.Trim().Replace("-", "+").Replace("_", "/"), "==");
                try
                {
                    byte[] base64 = Convert.FromBase64String(encoded);
                    guid = new Guid(base64);
                }
                catch (FormatException)
                {
                }
            }
            return guid;
        }
    }

 

posted @ 2018-08-05 19:44  tiasys  阅读(1561)  评论(0编辑  收藏  举报