ASP.NET Schedule deletion of temporary files

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

    Use the cache expiry notification to trigger file deletion:

        private static void DeleteLater(string path)
        {
            HttpContext.Current.Cache.Add(path, path, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 8, 0, 0), CacheItemPriority.NotRemovable, UploadedFileCacheCallback);
        }
    
        private static void UploadedFileCacheCallback(string key, object value, CacheItemRemovedReason reason)
        {
            var path = (string) value;
            Debug.WriteLine(string.Format("Deleting upladed file '{0}'", path));
            File.Delete(path);
        }
    

    ref: MSDN | How to: Notify an Application When an Item Is Removed from the Cache

提交回复
热议问题