Why does my code to download files produce corrupted PDFs?

Syed Mudhasir picture Syed Mudhasir · Jan 10, 2011 · Viewed 72.1k times · Source

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.

Answer

Mahmoud Farahat picture Mahmoud Farahat · Jan 10, 2011

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
        }
    }