我有一个代码,可以将文件压缩到文件夹中并下载 zip 文件 但下载后代码停在response.end()处 之后我有代码删除了文件夹中的所有文件,但它永远不会去那里。
有人知道为什么吗?
这是代码
protected void download_Click1(object sender, ImageClickEventArgs e)
{
string dirRoot = "E:\洗衣机\"; string[] filesToZip = Directory.GetFiles(dirRoot, "*.csv", SearchOption.AllDirectories); string zipFileName = string.Format("cleaned-{0:yyyy-MM-dd}.zip", DateTime.Now);
using (MemoryStream zipMS = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create, true))
{
foreach (string fileToZip in filesToZip)
{
if (new FileInfo(fileToZip).Extension == ".zip") continue;
if (fileToZip.Contains("node_modules")) continue;
byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip);
ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(fileToZip.Replace(dirRoot, "").Replace('\\', '/'));
using (Stream zipEntryStream = zipFileEntry.Open())
using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
{
zipFileBinary.Write(fileToZipBytes);
}
//lstLog.Items.Add("zipped: " + fileToZip);
}
}
using (FileStream finalZipFileStream = new FileStream("E:\\WashingMachine\\" + zipFileName, FileMode.Create))
{
zipMS.Seek(0, SeekOrigin.Begin);
zipMS.CopyTo(finalZipFileStream);
}
string filePath = "E:\\WashingMachine\\" + zipFileName +" ";
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
}
string[] directoryFiles = System.IO.Directory.GetFiles(dirRoot, "*.*");
foreach (string directoryFile in directoryFiles)
{
System.IO.File.Delete(directoryFile);
}
//lstLog.Items.Add("ZIP Archive Created.");
}
我已经改成这个了,现在可以用了
string filePath = "E:\\WashingMachine\\" + zipFileName + " ";
FileInfo file = new FileInfo(filePath);
string Outgoingfile = zipFileName;
if (file.Exists)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}