c# - 为什么我下载文件的代码会生成损坏的 PDF?

标签 c# .net pdf webclient

<分区>

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

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

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

最佳答案

检查这个方法,希望有帮助

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

关于c# - 为什么我下载文件的代码会生成损坏的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4644506/

相关文章:

c# - 将时间跨度格式化为 TotalMilliseconds

c# - 使用 C# 在 RichTextBox 中突出显示语法

c# - 未调用 UITableviewCell GetCell

c# - 仅处理来自某些程序集的未处理异常

c# - Json 解析失败

c# - 是否有任何工具可以将所有字段转换为一组 .cs 文件中的属性?

c# - 循环遍历列表并删除项目时,集合被修改错误

php - 如何将可变数据从数组传递到php中的fpdf

javascript - 在浏览器中以半页增量垂直放置嵌入的 PDF

python - 我可以使用 python 的 pdfminer 从 pdf 中提取亮点吗?