asp.net 下载文件,在Responce.end()处停止

6g8kf2rb  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(96)

我有一个压缩文件夹中的文件并下载zip文件的代码,但下载后,代码停止在response.end()。我有代码后,删除文件夹中的所有文件,但它从来没有去那里。
有人知道原因吗
这是密码

protected void download_Click1(object sender, ImageClickEventArgs e)
{

 string dirRoot = "E:\\WashingMachine\\";
 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.");
}
bvjxkvbb

bvjxkvbb1#

我已经改变了这个,现在它的工作

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();
}

相关问题