The input is not a valid Base-64 string as it contains a non-base 64 character
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);
Solution 1:
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:
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:
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:
Remove the unnecessary string through Regex
Regex regex=new Regex(@"^[\w/\:.-]+;base64,");
base64File=regex.Replace(base64File,string.Empty);
Solution 5:
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.