Creating Temporary Files in C#

Many programs create temporary files on your computer while they’re running. Temporary files are used to save data that’s either too large to be stored in memory, or need to be accessed by different resources, or needs to be persisted to allow smoother running of the application (almost like a cache).

Temporary files are stored under AppData/Local/Temp. The path is usually set in environment variables, and can be changed. If you go to %tmp% you’ll see a whole bunch of folders and files generated by various programs running on your machine.

If you need to create temporary files in your application, you can leverage the powerful System.IO.Path class.

Using Path.GetTempPath() will create a temporary file with a random* name in the temporary folder, and return the name of the newly created file.

It is the developer’s responsbility to either delete the file when it’s done being used, or leave it to the user to run disk cleaner.

If you need to create the temporary file for a specific use case and ensure it’s deleted, you can use FileOptions.DeleteOnClose option when creating your FileStream:

using (FileStream fs = new FileStream(Path.GetTempFileName(), 
       FileMode.Open, FileAccess.ReadWrite, FileShare.None, 4096, 
    //To Something with the file
}//File no longer exists


  1. MSDN

Author: Dev

Full Stack Developer at one of the largest Banks in Canada.