Getting a temporary filename with C# and .NET

Posted: (EET/GMT+2)

 

Storing temporary files is quite a common need, and the classes in .NET Framework library support this need well. The most commonly used routine is the GetTempFileName method of the Path class, part of the System.IO namespace.

Calling this static method returns a filename along with a full path, such as the following:

C:\Users\my.name\AppData\Local\Temp\tmp62E7.tmp

This useful method created a new file that you can later use to write to. However, the filenames are somewhat predictable, and always point to a certain folder. At times, you need a little extra security, and that's what the Path.GetRandomFileName method is for.

This method returns a cryptographically strong filename along with an extension, but no path. Thus, the returned string can be used both as a new folder name, or a filename. Here's an example of what is being returned:

rdxkd6l2.1cl

In case you need to create a temporary file, both these methods give you a helping hand. Note that GetRandomFileName does not attempt to create the file, so there's a tiny chance that a file with a similar name would already exists.

Happy coding!

PS. Remember to delete your temporary files once you are done with them!