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

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

I would do both; make the class disposable, and have the finalizer clean it up. There is a standard pattern for doing so safely and effectively: use it rather than attempting to deduce for yourself what the right pattern is. It is very easy to get wrong. Read this carefully:

http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

Note that you've got to be really really careful when writing a finalizer. When the finalizer runs, many of your normal assumptions are wrong:

  • There are all kinds of potentials for race conditions or deadlocks because you are no longer on the main thread, you're on the finalizer thread.

  • In regular code, if you're running code inside an object then you know that all the things the object refers to are alive. In a finalizer, all the things the object refers to might have just been finalized! Finalizers of dead objects can run in any order, including "child" objects being finalized before "parent" objects.

  • In regular code, assigning a reference to an object to a static field could be perfectly sensible. In a finalizer, the reference you are assigning could be to an already dead object, and therefore the assignment brings a dead object back to life. (Because objects referred to by static fields are always alive.) That is an exceedingly weird state to be in and nothing pleasant happens if you do.

  • And so on. Be careful. You are expected to fully understand the operation of the garbage collector if you write a non-trivial finalizer.