ASP.NET Schedule deletion of temporary files

前端 未结 8 1183
暗喜
暗喜 2021-01-06 00:38

Question: I have an ASP.NET application which creates temporary PDF files (for the user to download). Now, many users over many days can create many PDFs, which take much di

8条回答
  •  不要未来只要你来
    2021-01-06 01:31

    For each temporary file that you need to create, make a note of the filename 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
    

    Next, add the following cleanup code to global.asax:

    <%@ Application Language="C#" %>
    
    

    UPDATE: I'm now accually using a new (improved) method than the one described above. The new one involves HttpRuntime.Cache and checking that the files are older than 8 hours. I'll post it here if anyones interested. Here's 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();
                }
            });
        }
    }
    

提交回复
热议问题