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

Rohit Verma picture Rohit Verma · Feb 27, 2013 · Viewed 258.6k times · Source

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); 

Answer

bendecko picture bendecko · May 29, 2015

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...