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

DaveOnCSharp.com runs on the Thesis Theme


How smart is your Theme? How good is your support? Check out ThesisTheme for WordPress.

The Thesis Theme is one of the best Wordpress frameworks out there, especially if you understand software development, which since you're here you probably do. Thesis allows you to design post and page templates using a drag-and-drop system which gives you access to all the relevant page elements you would normally have to manually access through code. This is why understanding development techniques definitely helps, even though you don't need to write any code to get Thesis up and running.

So go check out the incredible features at DIYThemes and start using Thesis now!

10 comments… add one

  • TBossAZ

    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

        So,what is the difference between temp file and standard 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

    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

    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

    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

    Thanks Dave, really great and easy for understanding article !

  • Mj

    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