ASP.NET Schedule deletion of temporary files

前端 未结 8 1015
暗喜
暗喜 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:35

    Create a timer on Appication_Start and schedule the timer to call a method on every 1 hours and flush the files older than 8 hours or 1 day or whatever duration you need.

    0 讨论(0)
  • 2021-01-06 01:35
        private const string TEMPDIRPATH = @"C:\\mytempdir\";
        private const int DELETEAFTERHOURS = 8;
    
        private void cleanTempDir()
        {
            foreach (string filePath in Directory.GetFiles(TEMPDIRPATH))
            {
                FileInfo fi = new FileInfo(filePath);
                if (!(fi.LastWriteTime.CompareTo(DateTime.Now.AddHours(DELETEAFTERHOURS * -1)) <= 0)) //created or modified more than x hours ago? if not, continue to the next file
                {
                    continue;
                }
    
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception)
                {
                    //something happened and the file probably isn't deleted. the next time give it another shot
                }
            }
        }
    

    The code above will remove the files in the temp directory that are created or modified more than 8 hours ago.

    However I would suggest to use another approach. As Fredrik Johansson suggested, you can delete the files created by the user when the session ends. Better is to work with an extra directory based on the session ID of the user in you temp directory. When the session ends you simply delete the directory created for the user.

        private const string TEMPDIRPATH = @"C:\\mytempdir\";
        string tempDirUserPath = Path.Combine(TEMPDIRPATH, HttpContext.Current.User.Identity.Name);
        private void removeTempDirUser(string path)
        {
            try
            {
                Directory.Delete(path);
            }
            catch (Exception)
            {
                //an exception occured while deleting the directory.
            }
        }
    
    0 讨论(0)
提交回复
热议问题