guid to base64, for URL
I understand that the reason you are clipping == in the end is that because you can be certain that for GUID (of 16 bytes), encoded string will always end with ==. So 2 characters can be saved in every conversion.
Beside the point @Skurmedal already mentioned (should throw an exception in case of invalid string as input), I think the code you posted is just good enough.
One problem with using this technique to format a GUID for use in a URL or filename is that two distinct GUIDs can produce two values that differ only in case, e.g.:
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
Since URLs are sometimes interpreted as being case-insensitive, and in Windows file paths and filenames are case-insensitive. this could lead to collisions.
You might want to check out this site: http://prettycode.org/2009/11/12/short-guid/
It looks very close to what you're doing.
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;
}
}
If your method cannot convert the Base64 passed to it to a GUID, shouldn't you throw an exception? The data passed to the method is clearly erronous.