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

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

    Better yet would be to create the file with FileOptions.DeleteOnClose. This will ensure that the operating system forcibly deletes the file when your process exits (even in the case of a rude abort). Of course, you will still want to close/delete the file yourself when you are done with it, but this provides a nice backstop to ensure that you don't allow the files to be sit around forever

    Example:

    using (FileStream fs = File.Create(Path.GetTempFileName(), Int16.MaxValue, 
           FileOptions.DeleteOnClose)) 
    { 
    
        // Use temp file 
    
    } // The file will be deleted here
    

提交回复
热议问题