Daniel Peñalba
Daniel Peñalba

Reputation: 31847

What is the recommended way to copy a file to a tmp folder?

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

Answers (3)

Rhand
Rhand

Reputation: 897

  • Your code is working (although is does not do what you want, see next point)
  • No, GetRandomFileName doest not check for uniqueness of the name, I would advise using GetTempFileName() instead.
  • You do not have to check here, but when you start using the file (writing to it) errors maybe occur (e.g. full disk). If you use GetTempFileName() you do need to start checking for errors as it returns an error when it cannot create the file or there is no available unique name.

Upvotes: 2

Michael Goldshteyn
Michael Goldshteyn

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

Fredrik Mörk
Fredrik Mörk

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

Related Questions