2

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.

  • Is the following code correct?
  • Does it ensure that never try to copy to a location that already exists?
  • Is there any chance of failure? (Should I catch any exceptions)

The code that I am using is the following:

string tmpFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

Thanks in advance.

4

3 回答 3

3

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.

于 2011-10-26T14:08:23.863 回答
2
  • 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.
于 2011-10-26T14:14:06.693 回答
1

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.

于 2011-10-26T14:08:47.477 回答