GetTempFileName Method
.NET Framework Class Library
Path.GetTempFileName Method

Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.

Namespace: System.IO
Assembly: mscorlib (in mscorlib.dll)

Visual Basic (Declaration)
Public Shared Function GetTempFileName As String
Visual Basic (Usage)
Dim returnValue As String

returnValue = Path.GetTempFileName
C#
public static string GetTempFileName ()
C++
public:
static String^ GetTempFileName ()
J#
public static String GetTempFileName ()
JScript
public static function GetTempFileName () : String

Return Value

A String containing the full path of the temporary file.
Exception typeCondition

IOException

An I/O error occurs, such as no unique temporary file name is available.

- or -

This method was unable to create a temporary file.

This method creates a temporary file with a .TMP file extension.

The GetTempFileName method will raise an IOException if it is used to create more than 65535 files without deleting previous temporary files.

The GetTempFileName method will raise an IOException if no unique temporary file name is available. To resolve this error, delete all unneeded temporary files.

The following table lists examples of other typical or related I/O tasks.

To do this...

See the example in this topic...

Create a text file.

How to: Write Text to a File

Write to a text file.

How to: Write Text to a File

Read from a text file.

How to: Read Text from a File

Retrieve a file extension.

GetExtension

Retrieve the fully qualified path of a file.

GetFullPath

Retrieve the file name and extension from a path.

GetFileName

Retrieve only the file name from a path.

GetFileNameWithoutExtension

Retrieve only the directory name from a path.

GetDirectoryName

Change the extension of a file.

ChangeExtension

Determine if a directory exists.

Exists

Determine if a file exists.

Exists

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Wrapping the creation/deletion of a temporary file into a class      David M. Kean   |   Edit   |   Show History

Note: If you only need to open the temporary file once, then as mentioned by Catalin Pop Sever, it is better to pass the option FileOptions.DeleteOnClose when opening the file.

It is a common pattern to create a temporary file using Path.GetTempFileName, and wrap it in a try...finally block to ensure that it gets cleaned up:

C#:

string temporaryFile = null;
 
try
{
    temporaryFile = Path.GetTempFileName();
 
    // Use temporary file.
}
finally
{
    if (temporaryFile != null)
    {
        try
        {
            File.Delete(temporaryFile);
        }
        catch (IOException)
        {
        }
        catch (UnauthorizedAccessException)
        {
        }   
    }
}

 

Writing the above code over and over can become both tiresome and error prone. So instead, extract it into own class:

using System;
using System.IO;
 
namespace System.IO
{
    public class TemporaryFile : IDisposable
    {
        private bool _IsDisposed;
        private bool _Keep;
        private string _Path;
        
	public TemporaryFile() : this(false)
        {
        }
 
        public TemporaryFile(bool shortLived)
        {
            _Path = CreateTemporaryFile(shortLived);
        }
 
        public string Path
        {
            get { return _Path; }
        }
 
        public bool Keep
        {
            get { return _Keep; }
            set { _Keep = value; }
        }
 
        ~TemporaryFile()
        {
            Dispose(false);
        }
 
        public void Dispose()
        {
            Dispose(false);
            GC.SuppressFinalize(this);
        }
 
	protected virtual void Dispose(bool disposing)
        {
            if (!_IsDisposed)
            {
                _IsDisposed = true;
 
                if (!_Keep)
                {
                    TryDelete();  
                }
            }
        }
 
        private void TryDelete()
        {
            try
            {
                File.Delete(_Path);
            }
            catch (IOException)
            {
            }
            catch (UnauthorizedAccessException)
            {
            }
        }
 
        public static string CreateTemporaryFile(bool shortLived)
        {
            string temporaryFile = System.IO.Path.GetTempFileName();
 
            if (shortLived)
            {
                // Set the temporary attribute, meaning the file will live in memory and will not be written to disk
                File.SetAttributes(temporaryFile, File.GetAttributes(temporaryFile) | FileAttributes.Temporary);
            }
 
            return temporaryFile;
        }
    }
}

 

Using the new class is easy, just type the following:

using (TemporaryFile temporaryFile = new TemporaryFile())
{
// Use temporary file
}

 

If you decide, after constructing a TemporaryFile, that you want to prevent it from being deleted, simply set the TemporaryFile.Keep property to true:

using (TemporaryFile temporaryFile = new TemporaryFile()) 
{
temporaryFile.Keep = true;
}

 

Tags What's this?: Add a tag
Flag as ContentBug
Open the temporary file with DeleteOnClose      Catalin Pop Sever   |   Edit   |   Show History

A good programming pattern is to open temporary files with FileOptions.DeleteOnClose

// Note that File.Create() also overrides the file if it exists
using (FileStream fs = File.Create(Path.GetTempFileName(), Int16.MaxValue, FileOptions.DeleteOnClose)) {
	// Use temp file
}
// The file will be deleted here
Tags What's this?: Add a tag
Flag as ContentBug
Processing
Page view tracker