For each temporary file that you want to create, record the file name in the session:
// create temporary file: string fileName = System.IO.Path.GetTempFileName(); Session[string.Concat("temporaryFile", Guid.NewGuid().ToString("d"))] = fileName; // TODO: write to file
Then add the following cleanup code to global.asax:
<%@ Application Language="C#" %> <script RunAt="server"> void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. // remove files that has been uploaded, but not actively 'saved' or 'canceled' by the user foreach (string key in Session.Keys) { if (key.StartsWith("temporaryFile", StringComparison.OrdinalIgnoreCase)) { try { string fileName = (string)Session[key]; Session[key] = string.Empty; if ((fileName.Length > 0) && (System.IO.File.Exists(fileName))) { System.IO.File.Delete(fileName); } } catch (Exception) { } } } } </script>
UPDATE : I am now using a new (improved) method, different from the one described above. The new one includes HttpRuntime.Cache and checking that files are older than 8 hours. I will post it here if anyone is interested. Here is my new global.asax.cs :
using System; using System.Web; using System.Text; using System.IO; using System.Xml; using System.Web.Caching; public partial class global : System.Web.HttpApplication { protected void Application_Start() { RemoveTemporaryFiles(); RemoveTemporaryFilesSchedule(); } public void RemoveTemporaryFiles() { string pathTemp = "d:\\uploads\\"; if ((pathTemp.Length > 0) && (Directory.Exists(pathTemp))) { foreach (string file in Directory.GetFiles(pathTemp)) { try { FileInfo fi = new FileInfo(file); if (fi.CreationTime < DateTime.Now.AddHours(-8)) { File.Delete(file); } } catch (Exception) { } } } } public void RemoveTemporaryFilesSchedule() { HttpRuntime.Cache.Insert("RemoveTemporaryFiles", string.Empty, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, delegate(string id, object o, CacheItemRemovedReason cirr) { if (id.Equals("RemoveTemporaryFiles", StringComparison.OrdinalIgnoreCase)) { RemoveTemporaryFiles(); RemoveTemporaryFilesSchedule(); } }); } }
source share