问题:有更好的方法吗?

VB.Net

Function GuidToBase64(ByVal guid As Guid) As String
    Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "")
End Function

Function Base64ToGuid(ByVal base64 As String) As Guid
    Dim guid As Guid
    base64 = base64.Replace("-", "/").Replace("_", "+") & "=="

    Try
        guid = New Guid(Convert.FromBase64String(base64))
    Catch ex As Exception
        Throw New Exception("Bad Base64 conversion to GUID", ex)
    End Try

    Return guid
End Function

C#
public string GuidToBase64(Guid guid)
{
    return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "-").Replace("+", "_").Replace("=", "");
}

public Guid Base64ToGuid(string base64)
{
   Guid guid = default(Guid);
   base64 = base64.Replace("-", "/").Replace("_", "+") + "==";

   try {
       guid = new Guid(Convert.FromBase64String(base64));
   }
   catch (Exception ex) {
       throw new Exception("Bad Base64 conversion to GUID", ex);
   }

   return guid;
}

最佳答案

我知道最后剪切==的原因是因为可以确定对于GUID(16字节),编码字符串将始终以==结尾。因此,每次转换可以保存2个字符。

除了已经提到的@Skurmedal要点之外(如果输入的字符串无效,应该抛出异常),我认为您发布的代码就足够了。

关于c# - 引导到base64,用于URL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1032376/

10-09 12:37