Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file while it is being used by another process

Is it possible to copy a file which is being using by another process at the same time?

I ask because when i am trying to copy the file using the following code an exception is raised:

 System.IO.File.Copy(s, destFile, true); 

The exception raised is:

The process cannot access the file 'D:\temp\1000000045.zip' because it is being used by another process.

I do not want to create a new file, I just want to copy it or delete it. Is this possible?

like image 255
Vir Avatar asked May 29 '11 10:05

Vir


People also ask

How do I copy a locked file in Windows?

You can copy a locked file from a disk image or hard drive by using the file system browser in OSForensics. In the file system browser choose "Add device to case" from the File menu and select the drive letter or image file you wish to copy from.

How do I copy files to another simultaneously?

Hold Ctrl and click multiple files to select them all, no matter where they are on the page. To select multiple files in a row, click the first one, then hold Shift while you click the last one. This lets you easily pick a large number of files to copy or cut.

Can robocopy copy files in use?

That is a bad news that robocopy can not copy data in use , /XO can only copy newer files and that is good but what if the changes is inside a sheet or text ?


2 Answers

An Example (note: I just combined two google results, you may have to fix minor errors ;))

The important part is the FileShare.ReadWrite when opening the FileStream.

I use a similar code to open and read Excel documents while excel is still open and blocking the file.

using (var inputFile = new FileStream(     "oldFile.txt",     FileMode.Open,     FileAccess.Read,     FileShare.ReadWrite)) {     using (var outputFile = new FileStream("newFile.txt", FileMode.Create))     {         var buffer = new byte[0x10000];         int bytes;          while ((bytes = inputFile.Read(buffer, 0, buffer.Length)) > 0)         {             outputFile.Write(buffer, 0, bytes);         }     } } 
like image 116
Zebi Avatar answered Sep 23 '22 09:09

Zebi


To create a copy of a file that is read- and/or write-locked by another process on Windows, the simplest (and probably only) solution is to use the Volume Shadow Copy Service (VSS).

The Volume Shadow Copy Service is complex and difficult to call from managed code. Fortunately, some fine chaps have created a .NET class library for doing just this. Check out the Alpha VSS project on CodePlex: http://alphavss.codeplex.com.

EDIT

As with many of the projects on CodePlex, Alpha VSS has migrated to GitHub. The project is now here: https://github.com/alphaleonis/AlphaVSS.

like image 41
STLDev Avatar answered Sep 20 '22 09:09

STLDev