c# - 为什么下载的文件比输入流大?
问题描述
我正在编写一个 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.Lentgh
is17112
字节。我也确认bytes.Length
是17112
。
当我检查下载文件(它是一个 .xslx)时,它的大小是25983
字节。
此外,当我打开文件时,我收到一个警告,指出文件可能已损坏,但 Excel 能够修复它。
解决方案
我能够通过在 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
}
推荐阅读
- javascript - 有没有办法在过滤时获取过滤后数组的索引
- google-apps-script - 删除A列中的单元格时如何删除单个行中的多个单元格
- django-urls - 如何在视图中反转 Django 管理模板的 URL?
- python - 我将如何规范嵌套的 json
- angular - 我无法在 Agular 10 中更新服务中的值
- ios - 使用 Swift、Metal 和片段着色器在 iOS 上绘制椭圆
- powershell - Powershell If 语句从远程计算机获取操作系统架构
- c++ - Qt | 未触发 C++ 连接
- google-app-engine - 如何授予 gCloud App Engine 的公共访问权限
- swift - SWIFTUI 理解在模型中使用 CoreData 对象 (MVVM)