0

I call an API to get a PDF file. The API returns it as a string with binary data. Now I need to save it to a file without any conversion of the data. How can I do this in C#?

I have been trying

    string file = await service.GetDocumentsAsync(document.FileId);  //  Gets the filedata
    byte[] byteArray = file.Select (c => (byte)c).ToArray ();
    using (var stream = new FileStream($"c:\\temp\\{document.Id}.pdf", FileMode.Create))
    {
        stream.Write (byteArray,0,file.Length);
        stream.Close ();
    }

I do get the PDF, but it only has blank pages.

The beginning of the string when i look at it in the Debugger:

The beginning of the string when i look at it in the Debugger

10
  • 5
    "a string with binary data" what does that mean? Base64-encoded? Commented Nov 14, 2019 at 10:18
  • "string with binary data" like "0100101100" => How To Write A String Of Binary To File C# ; if it look like "aGVsbG8gd29ybGQK" => Base64 encoded string to file Commented Nov 14, 2019 at 10:20
  • What's wrong with File.WriteAllText("C:\\...", file);? Commented Nov 14, 2019 at 10:32
  • 1
    @Longoon12000 Because a PDF file will generally contain data which would be corrupted by treating it as a string (text) instead an treating it as bytes. Commented Nov 14, 2019 at 10:39
  • 1
    service.GetDocumentsAsync needs to give a byte[], not a string. Commented Nov 14, 2019 at 10:41

1 Answer 1

0

As suggested we had to change what the API returned. We use RestSharp and had to use Response.RawByte iso. Response.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.