c# - 应用程序/八位字节流在下载后用 NULL 填充文件的最后一行
问题描述
我正在尝试.hex
从服务器下载文件并将其保存在用户计算机上。文件大小略高于 2.4 MB。在用户机器上下载后,它达到 4 MB。额外的大小来自最后一行被 NULL 填充。NULL 计数与文件中的行完全相同 - 最后有 50 行 => 50 NULL(在我的情况下,最后有 32898 行(行)=> 32898 NULL)。
我尝试删除它们,但没有运气。在当前方法中有没有办法做到这一点?也欢迎使用 FileResult 的方法的替代方法。
public FileResult Download(string documentID) {
byte[] buffer = null;
using (FileStream fs = new FileStream("C:\\Temp\\temp\\" + documentID + ".hex", FileMode.Open, FileAccess.Read)) {
buffer = new byte[fs.Length - fs.Position];
fs.Read(buffer, 0, (int)fs.Length);
}
var cd = new System.Net.Mime.ContentDisposition {
FileName = "HEX_FILE_NAME.hex",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(buffer, "application/octet-stream");
}
解决方案
经过大量的头撞后,我设法找到了解决问题的方法。该文件被下载并且不再有额外的 NULL 行。也在实时服务器上对其进行了测试。也适用于其他文件扩展名。我将把解决方案留在这里,以防将来对某人有所帮助。
public FileResult Download(string documentID) {
string fileName = @"C:\\Temp\\temp\\" + documentID + ".hex";
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists) {
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.Flush();
Response.TransmitFile(fileInfo.FullName);
Response.End();
}
return File(fileName, "application/octet-stream");
}