The input is not a valid Base-64 string as it contains a non-base 64 character

C#File IoBase64

C# Problem Overview


I have a REST service that reads a file and sends it to another console application after converting it to Byte array and then to Base64 string. This part works, but when the same stream is received at the application, it gets manipulated and is no longer a valid Base64 string. Some junk characters are getting introduced into the stream.

The exception received when converting the stream back to Byte is

> The input is not a valid Base-64 string as it contains a non-base 64 > character, more than two padding characters, or a non-white space > character among the padding characters

At Service:

[WebGet(UriTemplate = "ReadFile/Convert", ResponseFormat = WebMessageFormat.Json)]  
public string ExportToExcel()
  {
      string filetoexport = "D:\\SomeFile.xls";
      byte[] data = File.ReadAllBytes(filetoexport);
      var s = Convert.ToBase64String(data);
      return s;
  }

At Application:

       var client = new RestClient("http://localhost:56877/User/");
       var request = new RestRequest("ReadFile/Convert", RestSharp.Method.GET);
       request.AddHeader("Accept", "application/Json");
       request.AddHeader("Content-Type", "application/Json");
       request.OnBeforeDeserialization = resp => {resp.ContentType =    "application/Json";};
       var result = client.Execute(request);
       byte[] d = Convert.FromBase64String(result.Content); 

C# Solutions


Solution 1 - C#

Check if your image data contains some header information at the beginning:

imageCode = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...

This will cause the above error.

Just remove everything in front of and including the first comma, and you good to go.

imageCode = "iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...

Solution 2 - C#

Very possibly it's getting converted to a modified Base64, where the + and / characters are changed to - and _. See http://en.wikipedia.org/wiki/Base64#Implementations_and_history

If that's the case, you need to change it back:

string converted = base64String.Replace('-', '+');
converted = converted.Replace('_', '/');

Solution 3 - C#

We can remove unnecessary string input in front of the value.

string convert = hdnImage.Replace("data:image/png;base64,", String.Empty);

byte[] image64 = Convert.FromBase64String(convert);

Solution 4 - C#

Remove the unnecessary string through Regex

Regex regex=new Regex(@"^[\w/\:.-]+;base64,");
base64File=regex.Replace(base64File,string.Empty);

Solution 5 - C#

Since you're returning a string as JSON, that string will include the opening and closing quotes in the raw response. So your response should probably look like:

"abc123XYZ=="

or whatever...You can try confirming this with Fiddler.

My guess is that the result.Content is the raw string, including the quotes. If that's the case, then result.Content will need to be deserialized before you can use it.

Solution 6 - C#

Just in case you don't know the type of uploaded image, and you just you need to remove its base64 header:

 var imageParts = model.ImageAsString.Split(',').ToList<string>();
 //Exclude the header from base64 by taking second element in List.
 byte[] Image = Convert.FromBase64String(imageParts[1]);

Solution 7 - C#

Probably the string would be like this data:image/jpeg;base64,/9j/4QN8RXh... First split for / and get the second token.

var StrAfterSlash = Face.Split('/')[1];

Then Split for ; and get the first token which will be the format. In my case it's jpeg.

var ImageFormat =StrAfterSlash.Split(';')[0];

Then remove the line data:image/jpeg;base64, for the collected format

CleanFaceData=Face.Replace($"data:image/{ImageFormat };base64,",string.Empty);

Solution 8 - C#

I arranged a similar context as you described and I faced the same error. I managed to get it working by removing the " from the beginning and the end of the content and by replacing \/ with /.

Here is the code snippet:

var result = client.Execute(request);
var response = result.Content
    .Substring(1, result.Content.Length - 2)
    .Replace(@"\/","/");
byte[] d = Convert.FromBase64String(response);

As an alternative, you might consider using XML for the response format:

[WebGet(UriTemplate = "ReadFile/Convert", ResponseFormat = WebMessageFormat.Xml)]  
public string ExportToExcel() { //... }

On the client side:

request.AddHeader("Accept", "application/xml");
request.AddHeader("Content-Type", "application/xml");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/xml"; };

var result = client.Execute(request);
var doc = new System.Xml.XmlDocument();
doc.LoadXml(result.Content);
var xml = doc.InnerText;
byte[] d = Convert.FromBase64String(xml);

Solution 9 - C#

var spl = item.Split('/')[1];
var format =spl.Split(';')[0];           
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);

Solution 10 - C#

As Alex Filipovici mentioned the issue was a wrong encoding. The file I read in was UTF-8-BOM and threw the above error on Convert.FromBase64String(). Changing to UTF-8 did work without problems.

Solution 11 - C#

And some times it started with double quotes, most of the times when you call API from dotNetCore 2 for getting file

string string64 = string64.Replace(@"""", string.Empty);
byte[] bytes = Convert.ToBase64String(string64);

Solution 12 - C#

I get this error because a field was varbinary in sqlserver table instead of varchar.

Solution 13 - C#

please check if there is no == as a postfix, just add == chars at last of string

// "........V/XeAeH/wALVWKtD8lz/AAAAABJRU5ErkJggg"
"........V/XeAeH/wALVWKtD8lz/AAAAABJRU5ErkJggg=="    /* yes */ 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRohit VermaView Question on Stackoverflow
Solution 1 - C#bendeckoView Answer on Stackoverflow
Solution 2 - C#Jim MischelView Answer on Stackoverflow
Solution 3 - C#Hasan Tuna OruçView Answer on Stackoverflow
Solution 4 - C#Amro MustafaView Answer on Stackoverflow
Solution 5 - C#Joe EnosView Answer on Stackoverflow
Solution 6 - C#Mahdi AlkhatibView Answer on Stackoverflow
Solution 7 - C#DevLoverUmarView Answer on Stackoverflow
Solution 8 - C#Alex FilipoviciView Answer on Stackoverflow
Solution 9 - C#mostafa kazemiView Answer on Stackoverflow
Solution 10 - C#testingView Answer on Stackoverflow
Solution 11 - C#user193679View Answer on Stackoverflow
Solution 12 - C#M KomaeiView Answer on Stackoverflow
Solution 13 - C#Mucahid UsluView Answer on Stackoverflow