Multi-threading issue with GetTempFilename()

Dec 21, 2009 at 5:56 PM


I'm currently using DotNetZip version 1.9 beta.

I'm using a bunch of threads to zip different files at the same time. There is no problem when the files are in different folders, but when two files are located in the same folder, I sometimes get the IOException :

"The file '<SomePath>\DotNetZip-aaaaaaaa.tmp' already exists."

The first problem resides in the fact that the file name is generated using a System.Random object, and it is not thread-safe. When the _rdn attribute is accessed by more than one thread, it may become corrupted, and _rdn.Next() will always return 0. This explains why the filename ends with As. This can be solved very easily using a lock on the _rdn attribute before calling Next().

The second problem is the fact that the generated name is validated using File.Exists() to ensure there is no conflicting file name. This is not enough to verify the uniqueness of the file name since the file may be created between the File.Exists() call and the new FileStream() call. I suggest using System.IO.Path.GetTempFileName() to get a temporary file, or to open the FileStream within the GetTempFilename() method.

Location of the code: \DotNetZip-src-v1.9.0.32\DotNetZip\Zip Partial DLL\Shared.cs



Dec 21, 2009 at 9:58 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.