Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The input is not a valid Base-64 string

Tags:

c#

base64

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.

like image 367
Omprakash Gaur Avatar asked May 19 '26 02:05

Omprakash Gaur


2 Answers

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();
like image 128
Hans Kilian Avatar answered May 20 '26 16:05

Hans Kilian


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.

like image 43
Trevor Avatar answered May 20 '26 14:05

Trevor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!