繁体   English   中英

c#- 写入响应时损坏的文件

[英]c#- Corrupt file when writing to Response

我正在尝试使用 ASP.Net 将文件写入输出响应流。 当我下载文件时,我Errors were found opening .zip file. You can extract files from this archive, but other programs may not be able to open it. Do you want to try fixing the problems?出现Errors were found opening .zip file. You can extract files from this archive, but other programs may not be able to open it. Do you want to try fixing the problems? Errors were found opening .zip file. You can extract files from this archive, but other programs may not be able to open it. Do you want to try fixing the problems? 错误。 但是,我可以取消此操作并正确打开 zip 文件。

我可能做错了什么?

ASP.Net\\C# 代码:

var pathToFile = "c:\abc.zip";
string fileName = Path.GetFileName(pathToFile);
byte[] buffer;
using (var fileStream = new FileStream(pathToFile, Filemode.open))
{
  buffer = new byte[fileStream. Length];
  fileStream.Read(buffer, 0, (int)fileStream.Length);
}
Response.Clear();
Response.Buffer = true;
Response.AppendHeader("content-disposition", string.Format(@"attachment; filename={0}.zip", filename));
Response.ContentType = "application/zip";
Response.AppendHeader("content-length", buffer.Length.ToString());
Response.WriteFile(pathToFile);

如果要使用buffer并将文件写入用户,请不要使用Response.WriteFile

更改为Response.OutputStream.Write ,并修改您的代码,如下所示:

var pathToFile = "c:\abc.zip";
string fileName = Path.GetFileName(pathToFile);
byte[] buffer = new byte[0];
using (var fileStream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read))
{
  buffer = new byte[fileStream.Length];
  fileStream.Read(buffer, 0, buffer.Length);
}
Response.Clear();
Response.AppendHeader("content-disposition", string.Format(@"attachment; filename={0}", filename));
Response.ContentType = "application/zip";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
Response.End();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM