Should Dispose() or Finalize() be used to delete temporary files?

后端 未结 8 1244
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 02:35

I have a class that makes use of temporary files (Path.GetTempFileName()) while it is active. I want to make sure these files do not remain on the user\'s hard driv

8条回答
  •  有刺的猬
    2021-02-04 03:04

    If you wish to re-use your temporary files e.g. open\close\read\write\etc, then clearing them up at the AppDomain unload level can be useful.

    This can be used in combination with putting temp files in a well known sub-directory of a temp location and making sure that the directory is deleted on application startup to ensure unclean shut-downs are taken care of.

    A basic example of the technique (with exception handling removed around delete for brevity). I use this technique in file-based unit tests where it makes sense and is useful.

    public static class TempFileManager
    {
        private static readonly List TempFiles = new List();
        private static readonly object SyncObj = new object();
    
        static TempFileManager()
        {
            AppDomain.CurrentDomain.DomainUnload += CurrentDomainDomainUnload;
        }
    
        private static void CurrentDomainDomainUnload(object sender, EventArgs e)
        {
            TempFiles.FindAll(file => File.Exists(file.FullName)).ForEach(file => file.Delete());
        }
    
        public static FileInfo CreateTempFile(bool autoDelete)
        {
            FileInfo tempFile = new FileInfo(Path.GetTempFileName());
    
            if (autoDelete)
            {
                lock (SyncObj)
                {
                    TempFiles.Add(tempFile);
                }
            }
    
            return tempFile;
        }
    }
    

提交回复
热议问题