4

I have a problem when downloading PDF files with the following code:

WebClient client = new WebClient();
client.DownloadFile(remoteFilename, localFilename);

Whereas other files are downloaded successfully, when I download and save a PDF document it shows a document repaired error when I try to open it.

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
Syed Mudhasir
  • 69
  • 1
  • 2
  • 5
  • 7
    What is the problem? – Andrew Bezzub Jan 10 '11 at 07:21
  • My problem is after downloading a pdf file and saving it as a pdf document thro above mentioned code. wen I try to open it shows document repaired error. – Syed Mudhasir Jan 10 '11 at 11:11
  • I hope this below link 'll help you... http://stackoverflow.com/questions/10829168/can-we-use-response-flush-instead-of-response-end/17038408#17038408 – Viishnuu Jun 11 '13 at 07:22
  • I don't think this question is answerable because so little information is provided. Through its use of `WebClient` and the term "download(ing)" it's clear this is about _client_-side code, so why are so many answers showing _server_-side code (and getting upvoted for it, too)? Where is the misunderstanding? – Lance U. Matthews Feb 04 '20 at 19:06

7 Answers7

7

check this method , hope that helps

        public static void DownloadFile(HttpResponse response,string fileRelativePath)
    {
        try
        {
            string contentType = "";
            //Get the physical path to the file.
            string FilePath = HttpContext.Current.Server.MapPath(fileRelativePath);

            string fileExt = Path.GetExtension(fileRelativePath).Split('.')[1].ToLower();

            if (fileExt == "pdf")
            {
                //Set the appropriate ContentType.
                contentType = "Application/pdf";
            }

            //Set the appropriate ContentType.
            response.ContentType = contentType;
            response.AppendHeader("content-disposition", "attachment; filename=" + (new FileInfo(fileRelativePath)).Name);

            //Write the file directly to the HTTP content output stream.
            response.WriteFile(FilePath);
            response.End();
        }
        catch
        {
           //To Do
        }
    }
Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59
2

Please try the Following code sample to download .pdf file.

 Response.ContentType = "Application/pdf"; 
 Response.AppendHeader("Content-Disposition", "attachment; filename=Test_PDF.pdf"); 
 Response.TransmitFile(Server.MapPath("~/Files/Test_PDF.pdf")); 
 Response.End();
Raaghav
  • 3,000
  • 1
  • 23
  • 21
  • This is server-side code whereas the question is asking about the use of `WebClient`, which is client-side. This is also essentially the same thing as [@MahmoudFarahat's answer](https://stackoverflow.com/a/4644637/150605) from over a year earlier. – Lance U. Matthews Feb 04 '20 at 18:59
1

@Syed Mudhasir: Its just a line :)

client.DownloadFileAsync(new Uri(remoteFilename, UriKind.Absolute), localFilename);

It will download pdf files. :)

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
JAVA
  • 11
  • 1
0

None of these solutions worked for me, or were not complete. Maybe this post was old and newer versions of .NET made it easier? Anyway, the following small code did the job for me so nicely:

  static async Task DownloadFile(string url, string filePath)
  {
     using (var wc = new WebClient())
        await wc.DownloadFileTaskAsync(url, filePath);
  }

And here how you can call the method:

Task.Run(async () => { await DownloadFile(url, filePath); }).Wait();
0
    public void DownloadPdf(String downloadLink, String storageLink)
    {
        using (WebClient wc = new WebClient())
        {
            wc.DownloadFile(downloadLink, storageLink);
        }
        Console.Write("Done!");
    }

    static void Main(string[] args)
    {
        Program test = new Program();
        test.DownloadPdf("*PDF file url here*", @"*save location here/filename.pdf*");
        Console.ReadLine();
    }

Make sure you add: using System.Net;

  • This is essentially the same code as in the question only wrapped in a method. Why would this code be expected to produce a readable file when the code in the question doesn't? – Lance U. Matthews Feb 04 '20 at 18:56
-1
public void DownloadTeamPhoto(string fileName)
{
  string mimeType = MimeAssistance.GetMimeFromRegistry(fileName);
  Response.ContentType = mimeType;
  Response.AppendHeader("Content-Disposition", "attachment; filename=" + 
  Path.GetFileName(basePath + fileName)); //basePath= @"~/Content/
  Response.WriteFile(basePath + fileName); //basePath= @"~/Content/
  Response.End();

}

public static string GetMimeFromRegistry(string Filename)
{
  string mime = "application/octetstream";
  string ext = System.IO.Path.GetExtension(Filename).ToLower();
  Microsoft.Win32.RegistryKey rk = 
  Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

  if (rk != null && rk.GetValue("Content Type") != null)
     mime = rk.GetValue("Content Type").ToString();

  return mime;
}
Rokive
  • 745
  • 9
  • 7
  • What is this even doing and how does it apply to the question? It seems to be figuring out the MIME type, so is this supposed to be run server-side? How do you know the server is running Windows and under the control of the downloading party? Where is the `WebClient` and file transfer? – Lance U. Matthews Feb 04 '20 at 18:42
-3

This worked for me:

string strURL = @"http://192.168.1.xxx/" + sDocumento;
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sDocumento + "\"");
byte[] data = req.DownloadData(strURL);
response.BinaryWrite(data);
response.End();
derloopkat
  • 6,232
  • 16
  • 38
  • 45
  • If you remove the references to the `System.Web` namespace, which was not specified in the question and implies this is server-side code, this becomes simply `WebClient req = new WebClient(); byte[] data = req.DownloadData(strURL);`, which is not all that different than what's in the question. So how does this solve the problem? – Lance U. Matthews Feb 04 '20 at 18:52