guid與Base64編碼互相轉換

guid的長度比較長,本文提供一種方法,將guid轉爲base64字符串,只有22位長度,比較好!ui

參考: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;
        }
    }
相關文章
相關標籤/搜索