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.
1 2 |
var tempFilePath = Path.GetTempFileName(); // something like C:\Users\USER\AppData\Local\Temp\tmp35C7.tmp |
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:
1 2 3 4 5 6 7 8 9 10 |
using (StreamWriter outputFile = new StreamWriter(tempFilePath)) { outputFile.WriteLine("This is a test"); } using (StreamReader inputFile = new StreamReader(tempFilePath)) { String line = inputFile.ReadToEnd(); Console.WriteLine(line); } |
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:
1 2 |
var file = new FileInfo(tempFilePath); file.Delete(); |
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.
1 2 3 |
// can give a performance boost - but measure first! FileInfo fileInfo = new FileInfo(tempFilePath); fileInfo.Attributes = FileAttributes.Temporary; |
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.
Hi, when I publich my asp mvc app on azure appservice I get D:\Local\Temp instead AppData\Local\Temp, how i can fix that?
Hi Abraham,
As https://serverfault.com/a/826730 suggests, this is the default behaviour of Azure App Services and cannot be changed.
Regards,
Johnny