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

57,784

Solution 1

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

Solution 2

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.

Solution 3

var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destFilePath, true);

The CopyTo method of FileInfo copies an existing file to a new file, allowing the overwriting of an existing file. That's why it doesn't break process working on existing file.

Solution 4

Well, another option is to copy the locked file somewhere by using Process class and invoke CMD to use the "copy" command. In most cases the "copy" command will be able to make a copy of the file even if it is in use by another process, bypassing the C# File.Copy problem.

Example:

try
{
File.Copy(somefile)
}
catch (IOException e)
{
 if (e.Message.Contains("in use"))
                        {

                            Process.StartInfo.UseShellExecute = false;
                            Process.StartInfo.RedirectStandardOutput = true;                           
                            Process.StartInfo.FileName = "cmd.exe";
                            Process.StartInfo.Arguments = "/C copy \"" + yourlockedfile + "\" \"" + destination + "\"";
                            Process.Start();                            
                            Console.WriteLine(Process.StandardOutput.ReadToEnd());
                            Proess.WaitForExit();
                            Process.Close();                          
                        }
}

the try/catch should be added on top of your current try/catch to handle the file in use exception to allow your code to continue... 

Solution 5

You should explore and find out which process is blocking the file. If this process is not yours, you have no way to solve the problem. Of course, you can apply some hacks and manually free the file lock but it's most likely that this approach will lead to unsuspected consequences. If the process is yours, try to unlock the file or lock it with share read access.

[EDIT]
The most easier way find out blocker process would be to use Process Explorer.Launch it and enter the file name in Find->Find Handle or DLL... dialog box. In the search results, you would be able to see which process is blocking your file. You also can do this job in C# check this: What process locks a file?. Also

Share:
57,784
Vir
Author by

Vir

nothing SPL

Updated on May 26, 2021

Comments

  • Vir
    Vir about 3 years

    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?

  • faester
    faester about 13 years
    Although you are right in your approach it is not always possible to read files locked by other processes; as GolezTrol mentions some files are also read locked. But your description never the less the correct approach and worth an upvote. I you manage to read - say - the attached ms sql data files using .NET i would be happy to learn how you do it.
  • Marcel Popescu
    Marcel Popescu over 10 years
    Why not inputFile.CopyTo(outputFile, 0x10000); ?
  • Panagiotis Kanavos
    Panagiotis Kanavos over 9 years
    Actually you can in NTFS, which is how all backup programs are able to backup opened files. They all use Journaling to detect changes, VSS to read files that are still open and sometimes, Transactions to ensure only consistent files are backed up.
  • GolezTrol
    GolezTrol over 9 years
    @PanagiotisKanavos I don't think that's common knowledge. If you could elaborate on that in an answer, you would make me, OP, and probably many others very happy.
  • cSteusloff
    cSteusloff over 6 years
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question.
  • zaitsman
    zaitsman about 4 years
    Can you explain how this might help?
  • Gokulnath
    Gokulnath about 4 years
    this worked for me, but not File.Copy ... I don't have an explanation.
  • Gertsen
    Gertsen almost 4 years
    I just tested this method, it did not work for me. Same exception as File.Copy.
  • Ariwibawa
    Ariwibawa over 3 years
    This didn't work when copying file currently opened by MS word.
  • Ariwibawa
    Ariwibawa over 3 years
    Using copy command did work for file still opened by MS word.
  • Dave Johnson
    Dave Johnson about 3 years
    Thanks for this. I was using a method from another question to check if a file was locked, and it was hanging, causing a bunch of problems. Getting rid of that and just using CopyTo works so far.
  • Ariwibawa
    Ariwibawa almost 3 years
    This work for file opened by msword, I've used cmd copy method and it was working. Until I tested my application on windows server 2019 (version 1809 OS Build 17763.2061), while the one that was worked was on build 17763.379.
  • pianocomposer
    pianocomposer about 2 years
    This is definitely a good, simple answer for the problem.