سؤال

والسؤال: هل هناك طريقة أفضل للقيام بذلك

و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 التي سبق ذكرها (يجب رمي استثناء في حالة سلسلة غير صالحة كمدخل)، وأعتقد أن الرمز الذي شارك هو جيد بما يكفي.

نصائح أخرى

وأنت قد ترغب في التحقق من هذا الموقع: <لأ href = "http://web.archive.org/web/20100408172352/http://prettycode.org/2009/11/12/short-guid/" يختلط = "noreferrer"> http://prettycode.org/2009/11/12/short-guid/

ويبدو قريبا جدا من ما تفعلونه.

public class ShortGuid
{
    private readonly Guid guid;
    private readonly string value;

    /// <summary>Create a 22-character case-sensitive short GUID.</summary>
    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("+", "-");
    }

    /// <summary>Get the short GUID as a string.</summary>
    public override string ToString()
    {
        return this.value;
    }

    /// <summary>Get the Guid object from which the short GUID was created.</summary>
    public Guid ToGuid()
    {
        return this.guid;
    }

    /// <summary>Get a short GUID as a Guid object.</summary>
    /// <exception cref="System.ArgumentNullException"></exception>
    /// <exception cref="System.FormatException"></exception>
    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;
    }
}

ومشكلة واحدة مع استخدام هذه التقنية لتنسيق GUID للاستخدام في URL أو اسم الملف هو أن اثنين من المعرفات الفريدة العمومية متميزة يمكن أن تنتج قيمتين التي تختلف فقط في حالة، منها مثلا:

    var b1 = GuidToBase64(new Guid("c9d045f3-e21c-46d0-971d-b92ebc2ab83c"));
    var b2 = GuidToBase64(new Guid("c9d045f3-e21c-46d0-971d-b92ebc2ab8a4"));
    Console.WriteLine(b1);  // 80XQyRzi0EaXHbkuvCq4PA
    Console.WriteLine(b2);  // 80XQyRzi0EaXHbkuvCq4pA

وبما أن تفسر عناوين بعض الأحيان بأنها حالة الأحرف، وفي Windows مسارات الملفات وأسماء الملفات حساسة لحالة الأحرف. وهذا يمكن أن يؤدي إلى التصادم.

إذا طريقتك لا يمكن تحويل باستخدام Base64 مرت عليه لGUID، لا ينبغي أن رمي استثناء؟ البيانات التي تم تمريرها إلى هذه الطريقة erronous بشكل واضح.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top