首页 > 解决方案 > 为什么下载的文件比输入流大?

问题描述

我正在编写一个 C# 方法来获取 MemoryStream 并将其作为文件下载到浏览器中。我使用 FileStream 加载一个 .xlsx 文件并将其复制到 MemoryStream

using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    docStream = new MemoryStream();
    fs.CopyTo(docStream);
}

然后我将 docStream 传递给 OpenXML 类

using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docStream, true))

并使用 OpenXML 类和方法更新内容。最后我将 docStream 传递给 DownloadStream 方法,但是下载的文件大于流的大小。

public class Utility
{
    public static void DownloadStream(MemoryStream inputStream, string filename)
    {
        byte[] bytes = inputStream.ToArray();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
        HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.BinaryWrite(bytes);
    }
}

我放了一个断点并验证了inputStream.Lentghis17112字节。我也确认bytes.Length17112

当我检查下载文件(它是一个 .xslx)时,它的大小是25983字节。

此外,当我打开文件时,我收到一个警告,指出文件可能已损坏,但 Excel 能够修复它。

标签: c#streamdownload

解决方案


我能够通过在 SO 中找到类似的问题来解决这个问题。它与编码无关。

问题是我需要添加:

HttpContext.Current.Response.End();

之后到我的 DownloadStream 方法BinaryWrite

public static void DownloadStream(MemoryStream inputStream, string filename)
{
    byte[] bytes = inputStream.ToArray();

    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
    HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.BinaryWrite(bytes);
    HttpContext.Current.Response.End(); // This is the key
}

推荐阅读