Response.TransmitFile并在传输后删除它

Rad*_*dhi 8 c# asp.net file-io gedcom response.transmitfile

我必须在我的网站上实施GEDCOM导出.

单击导出到gedcom时,我的.net代码在服务器上创建了一个文件.

然后我需要从服务器下载它到客户端,并且应该询问用户保存该文件的位置,这意味着需要savedialog.

下载后,我想从服务器删除该文件.

我有一个代码将文件从服务器传输到客户端:

Response.ContentType = "text/xml";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.TransmitFile(Server.MapPath("~/" + FileName));
Response.End();
Run Code Online (Sandbox Code Playgroud)

从这个链接

但是我无法在此代码之后删除文件作为Response.End结束响应,因此在该行之后写入的任何代码都不会执行.

如果我之前执行代码删除文件Response.End();,则文件不会传输,我收到错误.

Jos*_*osh 23

在Response.End之后放置的任何内容都不会被执行,因为它会抛出ThreadAbortException以在此时停止执行页面.

试试这个:

string responseFile = Server.MapPath("~/" + FileName);

try{
    Response.ContentType = "text/xml";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
    Response.TransmitFile(responseFile);
    Response.Flush();
}
finally {
    File.Delete(responseFile);
}
Run Code Online (Sandbox Code Playgroud)

  • 当用户在文件下载对话框中单击"取消"时,这不处理这种情况.发生这种情况时,会抛出HttpException,并显示消息"远程主机已关闭连接.错误代码为0x800703E3." 然后在finally块中,删除失败并出现IOException - "进程无法访问文件'C:\ Windows\TEMP\tmp5CA3.tmp',因为它正由另一个进程使用." 我在catch中添加了一个catch(HttpException)并调用了Response.End(),这对我有用 (6认同)