How to use Temporary Files in C#

Files and Directories, Operating System

What exactly is a temporary file? Put simply, a temporary file is a file used by an application for storing temporary data. There is no fixed rule which specifies what this data should be, but generally temporary files (or temp files) are used for storing ‘work data‘. For example Microsoft Office uses temp files to store backups of documents being created or edited. Other applications might use temp files to store large amounts of data which would otherwise occupy too much memory. Basically, it is up to the developer to decide what should be kept within his/her application’s temp files.

In Microsoft Windows, temp files end with the .tmp extension and by default are stored in C:\Users\[username]\AppData\Local\Temp.

The .NET Framework makes creating and using temp files a breeze, so let me show you how to use them.

Create a new Console Application and add a method called CreateTmpFile. In this method we will use the System.IO.Path class to create our temp file.

private static string CreateTmpFile()
{
    string fileName = string.Empty;

    try
    {
        // Get the full name of the newly created Temporary file. 
        // Note that the GetTempFileName() method actually creates
        // a 0-byte file and returns the name of the created file.
        fileName = Path.GetTempFileName();

        // Craete a FileInfo object to set the file's attributes
        FileInfo fileInfo = new FileInfo(fileName);

        // Set the Attribute property of this file to Temporary. 
        // Although this is not completely necessary, the .NET Framework is able 
        // to optimize the use of Temporary files by keeping them cached in memory.
        fileInfo.Attributes = FileAttributes.Temporary;

        Console.WriteLine("TEMP file created at: " + fileName);
    }
    catch (Exception ex)
    {
       Console.WriteLine("Unable to create TEMP file or set its attributes: " + ex.Message);
    }

    return fileName;
}

As you can see in the above code we are calling the GetTempFileName method of the Path class to create our temp file. When called, this method will automatically create the temp file in the correct folder according to your version of Windows. Then we are creating a FileInfo object and setting the Temporary attribute of our temp file. You can work without setting this attribute, but it is recommended to set it since the .NET Framework will optimize the way it uses your temp file if set.

And that’s all you need to do to create a temp file. The temp file’s name is automatically generated and looks something like this: tmpBD28.tmp.

Now let’s write some data to our temp file:

private static void UpdateTmpFile(string tmpFile)
{
    try
    {
        // Write to the temp file.
        StreamWriter streamWriter = File.AppendText(tmpFile);
        streamWriter.WriteLine("Hello from www.daveoncsharp.com!");
        streamWriter.Flush();
        streamWriter.Close();

        Console.WriteLine("TEMP file updated.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error writing to TEMP file: " + ex.Message);
    }
}

As you can see all we are doing here is opening the temp file using the StreamWriter class and then writing to it. It’s just like writing to a normal text file.

To read from the temp file is quite similar:

private static void ReadTmpFile(string tmpFile)
{
    try
    {
        // Read from the temp file.
        StreamReader myReader = File.OpenText(tmpFile);
        Console.WriteLine("TEMP file contents: " + myReader.ReadToEnd());
        myReader.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error reading TEMP file: " + ex.Message);
    }
}

Once you’re done using the temp file you need to delete it or else it will obviously remain there, and over time these files will end up filling your temp folder.

private static void DeleteTmpFile(string tmpFile)
{
    try
    {
        // Delete the temp file (if it exists)
        if (File.Exists(tmpFile))
        {
            File.Delete(tmpFile);
            Console.WriteLine("TEMP file deleted.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error deleteing TEMP file: " + ex.Message);
    }
}

Once you create all the above methods, you can call them for testing purposes as shown below:

static void Main(string[] args)
{
    string tmpFile = CreateTmpFile();
    UpdateTmpFile(tmpFile);
    ReadTmpFile(tmpFile);
    DeleteTmpFile(tmpFile);

    Console.ReadLine();
}

Another useful method within the Path class is the GetTempPath() method. This returns the path of the current system’s temporary folder, which you might want when working with temp files.

I hope you found this article useful. Feel free to add comments or ask any questions below.

Dave

13 comments… add one
  • TBossAZ Link Reply

    When you create a temporary file, should it not be automatically deleted when the computer is restarted?

    • As far as I know, Windows doesn’t automatically delete temp files unless the user schedules a cleanup job. However, you can set the file to be automatically deleted once your FileStream object goes out of scope. You can do this by using the FileOptions.DeleteOnClose flag.

      using (FileStream fs = File.Create(Path.GetTempFileName(), Int16.MaxValue, FileOptions.DeleteOnClose))
      {
          // Use temp file
      }
      
      • Yehudah Link Reply

        So,what is the difference between temp file and standard file?

        • Kevin Gómez Link Reply

          The difference is how you handle the directory of the file, on a tempfile the file is deleted when is closed but if you use an standard file you need develop more code to handle the directory and all the files in that directory.

      • Dave,
        Good article, thanks.
        I see a potential conflict in the “using” example to ensure a temp file is closed. Isn’t it true that both File.Create and GetTempFileName() both create a file? My understanding is that GetTempFileName() creates a 0-byte file when called. Please advise – it would be cool if it works…

        • Yes you are right about the GetTempFileName() creating a 0-byte file however this should still work because the File.Create() function will actually create or overwrite the given file name. So from what I can understand the file created by Path.GetTempFileName() is overwritten again with the same file name. If you test it out you can see that only one file is actually created in the %tmp% directory.

          Maybe a better way to do it would be to open a new FileStream instead of using File.Create():

          using (FileStream fs = new FileStream(Path.GetTempFileName(), FileMode.Open, FileAccess.ReadWrite, FileShare.None, Int16.MaxValue, FileOptions.DeleteOnClose))
          {
              // Use temp file
          }
          
  • Hi Dave, thank you for this insights about temporary files under .Net. I will integrate your code into my current project on codeplex (credits). Thx.

  • Terrell Link Reply

    Dave thanks for going over using temporary files. This article and your other one about multi-threading really helped me out. Great blog.

  • Rakesh Chandra G Link Reply

    Hi Dave… Nice article. I have a doubt. I have converted excel (.xls/.xlsx) to .csv files. According to my requirement, I should not store that .csv file in the client place. But I need to read the data from the csv file, which I have converted .So, is there any concept like in-memory to store it and read the data from that file….? Please let me know, if my question is not clear.

  • gatopeich Link Reply

    I don’t think changing a FileInfo structure will effect the file you got it from.

    What you really want is:
    File.SetAttributes(tempFilePath, FileAttributes.Temporary)

    • Both approaches work as far as I can tell. I had a look around to try and find which approach is best however I couln’t really find anything. However with my tests both ways worked.

  • Milos Link Reply

    Thanks Dave, really great and easy for understanding article !

  • Mj Link Reply

    Hi,
    There s some problem occuring due to insecure temporary files.. how do i solve that issue.. cos its persisting for a lot of projects in my solution.

Leave a Comment

Cancel reply