Reputation: 31
Facing issue for FromBase64String
method.
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
Tried replacing -
to +
var bytes = Convert.FromBase64String(id);
id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC"
Expected result is string should be converted to an equivalent 8-bit unsigned integer array.
Upvotes: 3
Views: 28195
Reputation: 8004
The input is not a valid Base-64 string
The exact reason you are getting this type of error is because it's not a valid Base64 string, instead as already mentioned, it's a Guid
; and not a valid Guid at that.
First you can check if you even have a valid Base64
string by trying to convert it.
public static bool StringIsBase64(string myString)
{
Span<byte> buffer = new Span<byte>(new byte[myString.Length]);
return Convert.TryFromBase64String(myString, buffer , out int bytesParsed);
}
Now if you call this function and it succeeds, then we would assume you do have a valid Base64
string, otherwise a conversion error would occur.
Your call can now look like this:
string id = "59216167-f9c0-4b1b-b1db-1babd1209f10@ABC";
var bytes;
if (StringIsBase64(id))
{
bytes = Convert.FromBase64String(id);
}
Something else I would like to address that none of the other answers addressed, is the input is not valid for even a Guid. A GUID is a 128-bit integer (16 bytes) and that string isn't valid.
You actually would receive the error:
Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
The characters @ABC
at the end of the string are causing this, if these are removed then we have an actual valid Guid
.
Upvotes: 2
Reputation: 1
Try this will Help
using System;
public class Program{
public static void Main()
{
Guid gg = Guid.NewGuid();
Console.WriteLine(gg);
string ss = Encode(gg);
Console.WriteLine(ss);
Console.WriteLine(Decode(ss));
}
public static string Encode(Guid guid)
{
string encoded = Convert.ToBase64String(guid.ToByteArray());
encoded = encoded.Replace("/", "_").Replace("+", "-");
return encoded.Substring(0, 22);
}
public static Guid Decode(string value)
{
value = value.Replace("_", "/").Replace("-", "+");
byte[] buffer = Convert.FromBase64String(value + "==");
return new Guid(buffer);
}
}
Upvotes: -2
Reputation: 25070
It's not a Base64 encoded string. It's a Guid. You can read it into a byte array like this
var bytearray = new Guid("59216167-f9c0-4b1b-b1db-1babd1209f10").ToByteArray();
Upvotes: 2