views:

337

answers:

3

Besides trying the operation and catching the exception, is there a method to determine if a file can be moved or copied?

+3  A: 

There is no way to know if a file move or copy will guaranteed succeed or not.

But you can check quite a few things to see if it will fail:

  • Check for disk space at the destination location (you need at least the size of your file)
  • Check for a file that already exists at the destination location
  • Do a file open, requesting read access on the source file to make sure 1) you have permissions to it, 2) it is not in use.
  • You can read the entire source file to make sure there are no locks inside the file.
  • A trick used by windows explorer when copying files (or moving across volumes) is to first create a blank file, then to extend the file to the full size. Only after the file is fully allocated, then writes start to happen into the file.
  • Allocating a file the size of the data you want to copy over will also tell you if there is a filesystem quote in place as well that has been reached.
  • If a file is in use, and you want to go this far, you could use Volume Shadow Copy (VSS).

More on file locking:

Please see my answer here for much more information on file locking & permissions in linux.

Please see my answer here for much more information on file locking & permissions in Windows.

Brian R. Bondy
A: 

In general, see if the File exists and that the current user has permission to read the file (or delete the file for move) and has the appropriate permission for the destination directory. As well, for copy, you should check that there is available disk space. Of course, before all that, make sure the original file and destination directory even exist.

Of course, this does not gurantee the operation will succeed. Many things can happen. Even the permissions for the file can change between the time you check and the time you do the operation.

BobbyShaftoe
A: 

If the file can be read, it can be moved or copied. Are you asking how you can check if the move or copy will succeed?

Stavros Korokithakis
Some filesystems allow read-only access, in which case a copy would be possible but not a move.
Tom