开发者

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

开发者 https://www.devze.com 2023-03-09 05:24 出处:网络
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:

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开发者_JS百科);

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?


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


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.


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.


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... 


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


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.


Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消