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

后端 未结 8 1237
隐瞒了意图╮
隐瞒了意图╮ 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:11

    A nice way is suggested by David M. Kean on the MSDN entry on Path.GetTempFileName. He creates a wrapper class implementing IDisposable that will automatically remove the file:

    public class TemporaryFile : IDisposable
    {
        private bool _isDisposed;
    
        public bool Keep { get; set; }
        public string Path { get; private set; }
    
        public TemporaryFile() : this(false)
        {
        }
    
        public TemporaryFile(bool shortLived)
        {
            this.Path = CreateTemporaryFile(shortLived);
        }
    
        ~TemporaryFile()
        {
            Dispose(false);
        }
    
        public void Dispose()
        {
            Dispose(false);
            GC.SuppressFinalize(this);
        } 
    
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
    
                if (!this.Keep)
                {
                    TryDelete();   
                }
            }
        }
    
        private void TryDelete()
        {
            try
            {
                File.Delete(this.Path);
            }
            catch (IOException)
            {
            }
            catch (UnauthorizedAccessException)
            {
            }
        }
    
        public static string CreateTemporaryFile(bool shortLived)
        {
            string temporaryFile = System.IO.Path.GetTempFileName();
    
            if (shortLived)
            { 
                // Set the temporary attribute, meaning the file will live 
                // in memory and will not be written to disk 
                //
                File.SetAttributes(temporaryFile, 
                    File.GetAttributes(temporaryFile) | FileAttributes.Temporary);
            }
    
            return temporaryFile;
        }
    }
    

    Using the new class is easy, just type the following:

    using (TemporaryFile temporaryFile = new TemporaryFile())
    {
        // Use temporary file
    }
    

    If you decide, after constructing a TemporaryFile, that you want to prevent it from being deleted, simply set the TemporaryFile.Keep property to true:

    using (TemporaryFile temporaryFile = new TemporaryFile()) 
    { 
        temporaryFile.Keep = true; 
    }
    

提交回复
热议问题