10

In an XML WebResponse I get a URL tag which has a link to a PDF file. Example of the URL value is: https://www.member-data.com/files/hb/c8955fc4d6160ec0fd87f4879c6496d3.pdf). I have to convert this PDF to a byte array, how do I do this in C#?

4 Answers 4

26

You can use WebClient.DownloadData, which has a default return value of a byte array. e.g.

byte[] bytes = myClient.DownloadData("https://www.member-data.com/files/hb/c8955fc4d6160ec0fd87f4879c6496d3.pdf");

Also, this assumes that you want the actual file in a byte array, not the content (text) of the PDF. That's a whole other ball of wax.

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

3 Comments

“which has a default return value of a byte array”. If this one is the default, does that this method has more possible return types?
Yes I want only contents of a pdf file.
THis pdf has images and I want those in a byte array.
16

You can use WebClient.DownloadData().

Comments

0

WebClient is obsolete. Use HttpClient instead:

string url = "requested/api/url/endpoint"

HttpClient client = new();
client.GetByteArrayAsync(url);

The GetByteArrayAsync is awaitable, so your method should be an async Task:

internal async Task<byte[]?> ReadFile()
{
   string url = "requested/api/url/endpoint"

   using HttpClient client = new();
   return client.GetByteArrayAsync(url);
}

Don't forget to dispose the HttpClient.

Comments

-2

To convert a PDF to a byte array use the static method ReadAllBytes in the System.IO namespace

1 Comment

On what class is this method? If you mean File.ReadAllBytes(), then that's not really applicable to downloading from a URL.

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.