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
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.
3 Comments
svick
“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?
user228777
Yes I want only contents of a pdf file.
user228777
THis pdf has images and I want those in a byte array.
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
To convert a PDF to a byte array use the static method ReadAllBytes in the System.IO namespace
1 Comment
svick
On what class is this method? If you mean
File.ReadAllBytes(), then that's not really applicable to downloading from a URL.