3

I am using the following code below to download Pdf from a url, i would like to have some idea what would be the best practise, I am just concern with performance and file size thanks.

using( WebClient wc = new WebClient() )
{
  byte[] data = wc.DownloadData("http://localhost:81/File/sample.pdf");

  Response.Clear();
  Response.ContentType = "application/pdf";
  Response.AppendHeader( "Content-Disposition" , "attachment;filename=data.pdf" );
  Response.BufferOutput = true;
  Response.AddHeader("Content-Length", data.Length.ToString());
  Response.BinaryWrite(data);
  Response.End();

}
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
Kachou
  • 83
  • 1
  • 1
  • 10

2 Answers2

6

If you are concerned about performance/efficiency/security I'd recommend using the framework's HttpClient using it you could do something like this:

using(var client = new HttpClient())
{
    var stream = await client.GetStreamAsync(url);

    // OR to get the content of the file as you do now
    var data = await client.GetByteArrayAsync(url);

    // do whatever you need to do with your file here
}
Luiso
  • 4,173
  • 2
  • 37
  • 60
2

If you're concerned about "performance and file size" (by which I assume you mean time on the wire), you're request for the *.pdf file should contain an accept-encoding header, something like this:

Accept-Encoding: gzip,deflate

Telling the server that you would prefer the pdf file compressed. Then, in your response, you should

  • Ensure that response body is suitably compressed in accordance with your requestor's accept-encoding header, and

  • Add the correct content-encoding header to your response. Something like

    Content-Encoding: gzip
    

If you need tools for compression and decompression, DotNetZip is great. Price is right, too.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135