如何在另一个进程使用文件时复制该文件

Vir*_*Vir 32 .net c# file-access file-copying

是否可以同时复制另一个进程正在使用的文件?

我问,因为当我尝试使用以下代码复制文件时,会引发异常:

 System.IO.File.Copy(s, destFile, true);
Run Code Online (Sandbox Code Playgroud)

提出的例外是:

该进程无法访问文件'D:\ temp\1000000045.zip',因为它正由另一个进程使用.

我不想创建新文件,我只想复制或删除它.这可能吗?

Zeb*_*ebi 36

一个例子(注意:我刚刚合并了两个谷歌搜索结果,你可能需要修复一些小错误;))

重要的是FileShare.ReadWrite打开FileStream的时候.

我使用类似的代码打开和读取Excel文档,而excel仍然打开并阻止文件.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不`inputFile.CopyTo(outputFile,0x10000);`? (7认同)
  • 虽然您的方法是正确的,但并不总是可以读取其他进程锁定的文件; 正如GolezTrol提到的那样,一些文件也被锁定.但是你的描述从来都不是正确的方法,值得投票.我设法阅读 - 比如说 - 使用.NET附加的ms sql数据文件我很乐意了解你是如何做到的. (2认同)

STL*_*Dev 9

要创建由Windows上的其他进程读取和/或写入锁定的文件的副本,最简单(也可能是唯一)的解决方案是使用卷影复制服务(VSS).

卷影复制服务很复杂,很难从托管代码调用.幸运的是,一些优秀的人员已经创建了一个.NET类库来实现这一目标.查看CodePlex上的Alpha VSS项目:http://alphavss.codeplex.com.

编辑

与CodePlex上的许多项目一样,Alpha VSS已迁移到GitHub.该项目现在在这里:https://github.com/alphaleonis/AlphaVSS.


Mic*_*eyM 6

那么,另一种选择是使用 Process 类将锁定的文件复制到某处,并调用 CMD 来使用“复制”命令。在大多数情况下,“复制”命令将能够复制文件,即使该文件正在被另一个进程使用,从而绕过 C# File.Copy 问题。

例子:

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... 
Run Code Online (Sandbox Code Playgroud)


小智 6

var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destFilePath, true);
Run Code Online (Sandbox Code Playgroud)

FileInfo 的 CopyTo 方法将现有文件复制到新文件,从而允许覆盖现有文件。这就是为什么它不会中断现有文件的处理过程。