第二次流式传输文件时出错

时间:2012-09-11 14:44:31

标签: c# asp.net

我在将文件流式传输到浏览器时遇到错误,但仅在第二次到第n次。它第一次正常工作。

C:\Users\gfinzer\AppData\Local\Temp\BTnADAkZ.pdf. could not be saved because the source file could not be read

以下是代码:

protected void Page_Load(object sender, EventArgs e)
{
    //Get the parameters
    string reportName = Utils.ParseStringRequest(Request, "reportName") ?? string.Empty;
    string reportGuid = Session["reportGuid"].ToString();
    string path = Path.Combine(ReportPath(), Utils.GetSessionReportName(reportName, reportGuid));

    using (var fileStream = File.Open(path, FileMode.Open))
    {
        Response.ClearHeaders();
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + reportName + "\"");
        Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture));
        StreamHelper.CopyStream(fileStream, Response.OutputStream);
        Response.Flush();
    }

}

这是CopyStream:

    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[32768];
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, read);
        }
    }

1 个答案:

答案 0 :(得分:1)

我可能错了,但您需要Response.End()之后的Flush来电吗?