Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically delete temp files in C#?

What's a good way to ensure that a temp file is deleted if my application closes or crashes? Ideally, I would like to obtain a temp file, use it, and then forget about it.

Right now, I keep a list of my temp files and delete them with an EventHandler that's triggered on Application.ApplicationExit.

Is there a better way?

like image 491
Nifle Avatar asked Dec 30 '08 12:12

Nifle


People also ask

Can C :\ TEMP be deleted?

In most cases the answer is yes!

Can I delete all files in C :\ temp?

Type temp and press Enter (or click OK) to open up the folder location and see your temp files. Hold Ctrl and click individual items to select them for cleanup. If you want to delete everything in your temp folder, press Ctrl + A to select all the items.

Is Temp folder automatically deleted?

Replies (7)  From its name , temp file contains temporary files and they will be deleted.


1 Answers

Nothing is guaranteed if the process is killed prematurely, however, I use "using" to do this..

using System; using System.IO; sealed class TempFile : IDisposable {     string path;     public TempFile() : this(System.IO.Path.GetTempFileName()) { }      public TempFile(string path)     {         if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");         this.path = path;     }     public string Path     {         get         {             if (path == null) throw new ObjectDisposedException(GetType().Name);             return path;         }     }     ~TempFile() { Dispose(false); }     public void Dispose() { Dispose(true); }     private void Dispose(bool disposing)     {         if (disposing)         {             GC.SuppressFinalize(this);                         }         if (path != null)         {             try { File.Delete(path); }             catch { } // best effort             path = null;         }     } } static class Program {     static void Main()     {         string path;         using (var tmp = new TempFile())         {             path = tmp.Path;             Console.WriteLine(File.Exists(path));         }         Console.WriteLine(File.Exists(path));     } } 

Now when the TempFile is disposed or garbage-collected the file is deleted (if possible). You could obviously use this as tightly-scoped as you like, or in a collection somewhere.

like image 72
Marc Gravell Avatar answered Oct 06 '22 00:10

Marc Gravell