为什么我的文件下载代码会生成损坏的PDF? [英] Why does my code to download files produce corrupted PDFs?

查看:321
本文介绍了为什么我的文件下载代码会生成损坏的PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码下载PDF文件时出现问题:

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

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

其他文件已成功下载,但是当我下载并保存PDF文档时,当我尝试打开它时,它显示了文档修复错误.

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.

推荐答案

检查此方法,希望对您有帮助

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

这篇关于为什么我的文件下载代码会生成损坏的PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆