Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a file can be moved or copied

Tags:

.net

file

copy

move

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

like image 668
user79755 Avatar asked Sep 03 '25 03:09

user79755


1 Answers

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.

like image 85
Brian R. Bondy Avatar answered Sep 05 '25 21:09

Brian R. Bondy