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

Vir picture Vir · May 29, 2011 · Viewed 50.9k times · Source

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?

Answer

Zebi picture Zebi · May 29, 2011

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);
        }
    }
}