【问题标题】:How to download, then delete file in ASP.NET properly?如何在 ASP.NET 中正确下载、删除文件?
【发布时间】:2016-08-16 09:18:05
【问题描述】:

我最近偶然发现了这个问题:在我的应用程序中,我为用户提供了从列表中下载多个文件的选项,方法是将它们放入 .zip 文件夹然后下载。我自然希望下载完成后删除该 .zip 文件夹。这是我的方法:

       try {

            Response.Clear();
            Response.ContentType = "application/zip";
            Response.AddHeader("Content-Disposition", "attachment; filename=filename.zip");
            Response.TransmitFile(archive);
            Response.Flush();
            success = success && true;

            return success;

        } catch {

            return false;

        } finally {

            System.IO.File.Delete(archive);
            Response.End();

        }

现在,布尔值只是表示下载是否成功,我认为它们现在并不重要。 我认为这是如何工作的,程序首先尝试将文件传输到客户端,如果没有发生错误,它会跳过 catch 块,并且只有 它被下载后才会删除archive 文件。

但是,我经常在System.IO.File.Delete(archive); 行上收到错误消息The process cannot access the file because it is being used by another process.。这并不是每次都会发生,据我所知,这是相当随机的。 谁能提示我解决方案?

【问题讨论】:

  • 不要使用Response.TransmitFile,而是手动打开并发送文件,同时在删除文件之前关闭连接。

标签: asp.net file downloading-website-files


【解决方案1】:
 Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition",
                    "attachment; filename=myFile.txt");
    Response.WriteFile(Server.MapPath("~/uploads/myFile.txt"));
    Response.Flush();
    System.IO.File.Delete(Server.MapPath("~/uploads/myFile.txt"));
    Response.End();

【讨论】:

  • 谢谢,我试试这个看看会发生什么:)
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 2018-07-29
  • 2023-03-04
  • 1970-01-01
  • 2014-12-05
相关资源
最近更新 更多