guid与Base64编码互相转换
Posted tiasys
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } }
以上是关于guid与Base64编码互相转换的主要内容,如果未能解决你的问题,请参考以下文章