Working with Temporary Files in .Net
Working with files in .Net is straightforward. You can use the File or FileInfo classes and call the method with the self-explaining name to create, copy, move or delete files on your system.
However, sometimes all you care about is to write some temporary data to a file. In this case the Path.GetTempFileName() method is exactly what you need. This method creates a uniquely named, zero-byte file in the user's temporary folder and returns the full path of that file.
There is no need for you to figure out a random name and a location to store your file. You can take the path to that temporary file and work with it as you would do with any other file:
Delete your temporary files
An often overlooked little catch is that his temporary file will not be automatically removed from the file system when your application closes. Since you can create up to 65535 temporary files before you run into an exception, it may take a long time until you figure this out.
As soon as you no longer need this temporary file, you should delete it:
Performance optimisation
If you need an awful lot of temporary files that are short-lived and small, you may be able to gain some performance benefits by explicitly setting the temporary flag in the file attributes. That flag tells the system to hold as much as possible in the system cache without writing it to the disk.
Before you go and change all usages of temporary files, please make a performance test. Solid State Disks (SSD) have changed much of the old truths about storage systems and updating the firmware may give you much bigger performance gains than setting this flag.
Conclusion
The method Path.GetTempFileName() is a great help for all applications that need to save temporary data. Just remember to remove your files when you no longer need them.