Home of the AlmostImplementedException

Limitation of Path.GetTempFileName

Welcome to a short trip to a concrete function of the .Net Framework: Path.GetTempFileName
In my current project we have a lot of unit tests where a lot of temp files (created by Path.GetTempFileName) are used and a build server that builds the projects and executes the unit tests.
Some week ago we noticed that the build server needs a lot of time to complete his operations with a high CPU load.
We figured out that the problem was caused by the temporary files. After out investigation of the temporary folder we detected about 65k files with names like “tmp0F45.tmp”.
So we cleaned the temporary folder and started a new build operation. All works fine.
The problem was caused – as expected – by the temporary files created by Path.GetTempFileName. But why? When we take a closer look at the temporary file name pattern we will notice that it contains 4 hex digits – So if we have a range from 0x0000 to 0xFFFF (0 – 65535). This is also described in the MSDN about the Path.GetTempFileName function. (MSDN: Path.GetTempFileName)

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

You can test this behaviour with the following snippet:

Warning: Please keep in mind that this will create thousands of temporary files in your temp folder. Use the following in a command prompt to cleanup the created files: “DEL %TEMP%\tmp????.tmp”
On my system after the creation of 47k files the time raised up from ~0,4s to ~2,8s. The last package of 1024 temp files takes much longer and at the last file we will cause an IOException. So never forget to cleanup the temporary files you create or use your own logic to create temporary files, for example a guid as filename.

Share :

, , , , , , , , ,

Leave a Reply