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 th
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);
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);
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);
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.
var spl = item.Split('/')[1];
var format =spl.Split(';')[0];
stringconvert=item.Replace($"data:image/{format};base64,",String.Empty);