File.Copy() giving system.IO.IOException: The process cannot access the file ..because it is being used by another process. exception

shoab picture shoab · Apr 5, 2011 · Viewed 8.4k times · Source

i am using File.Copy(..,..) method in my asp.Net app it is showing me system.IO.IOException: The process cannot access the file ..because it is being used by another process.

any work around for it

thanks in advance

Answer

Simen S picture Simen S · Apr 5, 2011

You have to either a) stop the process which is using the file or b) wait until the file isn't being used anymore.

You should read this wikipedia entry on File Locking. Pay particular attention to the "In Microsoft Windows" paragraph where you will get a better idea about how file locking works.

If another program has opened the file with the sharing mode parameter stating that the file will not be shared even for read-access, then there is nothing you can really do to force the copying operation from your application.

If you are keen to "play god", and you are willing kill processes that may be holding a lock on the files you are concerned with, then you can attempt to find out which process is holding on to your file using the information in this thread: How do I find out which process is locking a file using .NET?

A better strategy is probably to investigate why the file that your are copying is being locked, and whether it is possible to avoid the lock conflict, by setting restrictive file permissions on the file(s), or by reconfiguring the software which is competing for the lock on the file. E.g. If an antivirus program occasionally scans a folder structure used by your app, then you can perhaps tell the software to ignore that particular folder.

If execution time is not critical you can perhaps delay or postpone your copy operation. A simple strategy would be to get-that-locked-file-on-the-next-iteration-instead. Another strategy could involve listening for events e.g. from the FileSystemWatcher class, with the idea to Wait until file is unlocked in .NET