读一个二进制文件,并使用Response.BinaryWrite() [英] Reading a binary file and using Response.BinaryWrite()

查看:927
本文介绍了读一个二进制文件,并使用Response.BinaryWrite()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要读取文件系统中的PDF文件,然后写出来给用户的应用程序。该PDF是183KB,似乎很好地工作。当我使用code底部的浏览器获得一个224KB的文件,我得到从Acrobat Reader一条消息说该文件已损坏,无法修复。

下面是我的code(我也试过用File.ReadAllBytes(),但我得到同样的事情):

 使用(的FileStream FS = File.OpenRead(路径))
{
    INT长度=(INT)fs.Length;
    字节[]缓冲区;    使用(BinaryReader BR =新BinaryReader(FS))
    {
        缓冲液= br.ReadBytes(长);
    }    Response.Clear();
    将Response.Buffer =真;
    Response.AddHeader(内容处置的String.Format(附件;文件名= {0},Pa​​th.GetFileName(路径)));
    Response.ContentType =应用程序/+ Path.GetExtension(路径).Substring(1);
    Response.BinaryWrite(缓冲液);
}


解决方案

尝试添加

到Response.End();

在调用Response.BinaryWrite()。

您可能无意中发送Response.BinaryWrite回来后,其他内容可能混淆的浏览器。到Response.End将确保浏览器只得到什么你真的打算。

I have an app that needs to read a PDF file from the file system and then write it out to the user. The PDF is 183KB and seems to work perfectly. When I use the code at the bottom the browser gets a file 224KB and I get a message from Acrobat Reader saying the file is damaged and cannot be repaired.

Here is my code (I've also tried using File.ReadAllBytes(), but I get the same thing):

using (FileStream fs = File.OpenRead(path))
{
    int length = (int)fs.Length;
    byte[] buffer;

    using (BinaryReader br = new BinaryReader(fs))
    {
        buffer = br.ReadBytes(length);
    }

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
    Response.ContentType = "application/" + Path.GetExtension(path).Substring(1);
    Response.BinaryWrite(buffer);
}

解决方案

Try adding

Response.End();

after the call to Response.BinaryWrite().

You may inadvertently be sending other content back after Response.BinaryWrite which may confuse the browser. Response.End will ensure that that the browser only gets what you really intend.

这篇关于读一个二进制文件,并使用Response.BinaryWrite()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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