[英]When to delete generated file using asp.net
我有一个模板excel文件,可以从中生成excel文件。
我的代码如下(这部分是从模板创建一个新的excel文件):
string currentFN = PropertyFinalResult[0].Fecha;
string fixCurrentFN = currentFN.Replace('/', '_');
string currentTime = DateTime.Now.ToLongTimeString();
string fixCurrentTime = currentTime.Replace(':', '_');
string addToFileName = fixCurrentTime.Replace(' ', '_');
string newFN = fixCurrentFN + "-" + addToFileName;
string SourceFile = Request.PhysicalApplicationPath + "Template\\ExcelTemplate.xlsx";
string DestFile = Request.PhysicalApplicationPath + "Template\\" + newFN + ".xlsx";
//To keep FileName for posterior deletion
Session["sDestFile"] = DestFile;
try
{
File.Copy(SourceFile, DestFile);
}
catch (Exception ex)
{
lblErrorSavingToDB.Text = "Error: " + ex.Message;
lblErrorSavingToDB.Visible = true;
}
之后,我打开新的excel文件,将记录插入其中,然后通过执行以下操作将文件流式传输给用户:
//Streaming file to client
string fileName = newFN + ".xlsx";
Response.Redirect("../Template/" + fileName);
现在,我的问题是,用户是否保存文件,何时删除生成的文件? 我希望用户关闭有关“打开”或“保存文件”的弹出窗口。 但是如何知道用户何时关闭该窗口?
您可以使用TransmitFile
,然后在传输结束后关闭。 例:
try
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename=\"" + Path.GetFileName(path.FullName) + "\"");
Response.AddHeader("content-length", path.Length.ToString());
Response.TransmitFile(path.FullName);
Response.Flush();
}
finally
{
File.Delete(Server.MapPath("~/"+tpacode+".zip"));
}
何时删除文件(或者最好说“保留文件多长时间”)是一个最好由应用程序的业务规则回答的问题。
过去,在低流量应用程序中,我使用“清理”例程删除早于特定阈值的文件。 创建新文件时将执行该清理,届时指定文件夹中早于阈值的任何文件都将被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.