字节数组不写入pdf流c#

时间:2018-01-22 22:20:39

标签: c# arrays pdf byte mime-types

我有一个字节数组,其中包含所需的所有数据,并且可以在pdf中显示,如果我使用此代码,则可以打开该文件:

System.IO.File.WriteAllBytes(@"C:\Users\Person\Downloads\results.pdf", bytes) 

让我知道字节数组应该是好的。问题是我正在尝试动态创建pdf,当我在开发工具的网络选项卡中查看调用时,它显示200并在响应选项卡中我得到文本响应。当我在文本编辑器中复制该响应并将其另存为pdf时,它具有正确的页面数量,但没有数据。所以我在这里有两个问题。由于某种原因,它不会作为pdf返回,并且字节数组没有写入它。关于我能做什么的任何建议?我整天看着堆栈溢出,并尝试过各种各样的事情,包括将contentType设置为application / pdf。

byte[] bytes = ms.ToArray();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer = true;
response.AddHeader("Accept-Header", bytes.Length.ToString());
response.AddHeader("Content-Length", bytes.Length.ToString());
response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
response.AddHeader("Content-Description", "File Download");
response.ContentType = "application/octet-stream";
response.OutputStream.Write(bytes, 0, onvert.ToInt32(bytes.Length));

//I've tried using this as well
//response.BinaryWrite(bytes);
response.Flush();
response.End();

更新代码:

     byte[] bytes = ms.ToArray();

        HttpResponse response = HttpContext.Current.Response;
        try
        {
            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.AddHeader("Accept-Header", bytes.Length.ToString());
            response.AddHeader("Content-Length", bytes.Length.ToString());
            response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
            response.ContentType = "application/pdf";
            response.BinaryWrite(bytes);
            response.Flush();
        }
        catch { }
        finally
        {
            response.End();
        }

1 个答案:

答案 0 :(得分:0)

我得到了它的工作:

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.ContentType = "application/pdf";
            response.AddHeader("content-disposition", "attachment; filename=Results.pdf");
            response.BinaryWrite(bytes);
            response.Flush();
            response.Close();