2015-09-16 49 views
1

我正在编写一个应用程序,用户将生成用户可以查看的文件,然后选择下载,如果它看起来不错。该应用程序将文件写入服务器以下列方式:如何在结束MVC应用程序时删除文件?

private void WriteTestFileToServer(MyFile file) 
    { 
     string serverPath = "~/MyFiles"; 
     string fileName = "/FileExport" + "_" + file.FromDate.ToString("yyyyMMdd") + "_" + 
      file.ToDate.ToString("yyyyMMdd") + "_" + file.RunTime.ToString("yyyyMMdd") + ".txt"; 
     StreamWriter sw = new StreamWriter(Server.MapPath(serverPath + fileName), true); 
     foreach (var row in file.Rows) 
     { 
      sw.WriteLine(row.ToFileFormat()); 
     } 
     sw.Close(); 
    } 

会话结束后,即在用户退出我想产生要删除的所有文件浏览器。是否有任何处理我可以附加做一些清理工作?还是有更好的方法来存储会话期间的文件,以便文件不必写入磁盘?

请注意,我希望能够将该文件作为应用程序中的Href链接进行访问。

+0

您可以处理'保护无效Session.End(object sender,EventArgs e)'在'global.aspx'文件中,但是只有当你将某些东西保存到'Session'中时才会触发该事件 –

回答

1

当会话过期时,您没有太多的控制权。

一种解决方案是将文件内容保存在用户会话中,并将其显示在控制器操作上。 .net将负责为您清理会话。

public ActionResult GetFile() 
{ 
    // file content from session 
    string fileContent = (string)HttpContext.Session["file"]; 

    byte[] contentAsBytes = new System.Text.UTF8Encoding().GetBytes(fileContent); 
    return File(contentAsBytes, "text/plain"); 
} 
0

添加您的代码在Global.asax.cs中保存Session_End中方法:

protected void Session_End(object sender, EventArgs e) 
{ 
... 
} 

或者你也可以使用应用程序级的事件:

protected void Application_End(object sender, EventArgs e) 
{ 
... 
} 
相关问题