Reputation: 31847
I need to copy a file to a tmp location in order to manipulate it. I need to ensure that I always can copy the file.
The code that I am using is the following:
string tmpFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Thanks in advance.
Upvotes: 2
Views: 4073
Reputation: 897
Upvotes: 2
Reputation: 74340
What's wrong with:
string tmpFile = Path.GetTempFileName();
From MSDN on Path.GetTempFileName():
Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file. The file has a .TMP extension.
It does ensure that you don't get a file that already exists and with regard to your question about failure scenarios, if it cannot create such a file:
The GetTempFileName method will raise an IOException if it is used to create more than 65535 files without deleting previous temporary files.
The GetTempFileName method will raise an IOException if no unique temporary file name is available. To resolve this error, delete all unneeded temporary files.
Upvotes: 1
Reputation: 158299
Perhaps use Path.GetTempFileName
instead?
string tmpFile = Path.GetTempFileName();
That method may throw IOException
so you should probably catch that at some point. Exactly where depends more on the context in which this code exists.
Note that this method also creates the file on disk, so there is no risk that some other process creates an identically named file between this call and the time when the file is written to by your code.
Upvotes: 3