我有一个应用程序需要从文件系统读取 PDF 文件,然后将其写出给用户。 PDF 为 183KB,似乎可以完美运行。当我使用底部的代码时,浏览器得到一个 224KB 的文件,我从 Acrobat Reader 收到一条消息,说该文件已损坏且无法修复。
这是我的代码(我也试过使用 File.ReadAllBytes(),但我得到了同样的结果):
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);
}
最佳答案
尝试添加
Response.End();
在调用 Response.BinaryWrite() 之后。
您可能会在 Response.BinaryWrite 之后无意中发送回其他内容,这可能会使浏览器感到困惑。 Response.End 将确保浏览器只获得您真正想要的内容。
关于c# - 读取二进制文件并使用 Response.BinaryWrite(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/848679/