45

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?

STLDev
  • 5,950
  • 25
  • 36
Vir
  • 1,294
  • 1
  • 13
  • 23
  • Is that file blocked by your app? – Anton Semenov May 30 '11 at 08:19
  • I don't Know it is blocked by my app or not cause i am creating a zip file using using ICSharpCode.SharpZipLib.Zip reference after zip i copy that and export it and After Export when i again want to delete that fileit shows exception. – Vir May 30 '11 at 08:24

7 Answers7

48

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);
        }
    }
}
kara
  • 3,205
  • 4
  • 20
  • 34
Zebi
  • 8,682
  • 1
  • 36
  • 42
  • 4
    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. – faester May 29 '11 at 11:00
  • 8
    Why not `inputFile.CopyTo(outputFile, 0x10000);` ? – Marcel Popescu Nov 01 '13 at 11:10
  • This didn't work when copying file currently opened by MS word. – Ariwibawa Feb 15 '21 at 11:14
12

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.

STLDev
  • 5,950
  • 25
  • 36
6
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.

darklech
  • 69
  • 1
  • 1
  • 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. – Dave Johnson Jun 02 '21 at 14:24
  • 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. – Ariwibawa Aug 05 '21 at 09:21
  • This is definitely a good, simple answer for the problem. – pianocomposer May 17 '22 at 22:53
5

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... 
MickeyM
  • 59
  • 1
  • 2
4

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

Community
  • 1
  • 1
Anton Semenov
  • 6,227
  • 5
  • 41
  • 69
-2

No you can't. Some programs won't lock the file for reading, but if they do, you can't get to the file without killing the other program.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • 4
    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. – Panagiotis Kanavos Jan 09 '15 at 13:58
  • 6
    @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. – GolezTrol Jan 09 '15 at 15:53
-4

Try:

var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destinationFilePath, true);
Gokulnath
  • 1,166
  • 15
  • 29