Skip to content

What is the Difference Between Path.GetTempFileName and Path.GetTempPath

Updated: at 11:18 PM

Getting filenames to use as scratch files is usually very straight forward.  Well, today, I found out “not so much”.  I decided today was a good day to tackle the problem of why is my file synchronization product we are about to release still littering my tmp directory with files when it finishes.  Turns out, it’s the subtle difference between the above two Path member functions GetTempFileName and GetTempPath.

The big difference is that GetTempFileName actually creates a file where as GetTempPath simply tells you where the file is going to be.

Here are some words out of MSDN for Path.GetTempFileName

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

And For Path.GetTempPath

The path to the temporary folder, ending with a backslash.

Subtle, but clear when you read the doc.  If you read the community content, there is a humorous discussion with someone saying “you might as well use the other one, it does the same thing”.  All I can say to that is read the docs!  I got stung today, but never again.

I’m now creating my filename with a string as follows which kind of does the same thing, but not really. 

 

public static string GetTempFileWithGuid(string filePrefix)
{
string retFileName = string.Format("{0}{1}{2}.crsync",
Path.GetTempPath(), filePrefix, Guid.NewGuid());
return retFileName;
}

HTH’s.