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

发布于 2024-11-11 04:51:43 字数 267 浏览 4 评论 0原文

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

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

 System.IO.File.Copy(s, destFile, true);

引发的异常是:

该进程无法访问文件“D:\temp\1000000045.zip”,因为该文件正在被另一个进程使用。

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

没有你我更好 2024-11-18 04:51:43

一个示例(注意:我刚刚组合了两个谷歌结果,您可能需要修复小错误;))

重要的部分是打开 FileStream 时的 FileShare.ReadWrite

我使用类似的代码打开并读取 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);
        }
    }
}

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);
        }
    }
}
你怎么敢 2024-11-18 04:51:43

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

卷影复制服务很复杂并且难以从托管代码调用。幸运的是,一些优秀的人已经创建了一个 .NET 类库来完成此任务。查看 CodePlex 上的 Alpha VSS 项目:http://alphavss.codeplex.com

编辑

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

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.

云归处 2024-11-18 04:51:43

那么,另一种选择是使用 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... 

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... 
纸短情长 2024-11-18 04:51:43
var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destFilePath, true);

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

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.

开始看清了 2024-11-18 04:51:43

您应该探索并找出哪个进程正在阻止该文件。如果这个过程不是你的,你就没有办法解决问题。当然,您可以应用一些技巧并手动释放文件锁,但这种方法很可能会导致意想不到的后果。如果该进程是您的,请尝试解锁该文件或使用共享读取访问权限锁定该文件。

[编辑]
找出阻止进程的最简单方法是使用 Process Explorer。启动并在Find->Find Handle or DLL...对话框中输入文件名。在搜索结果中,您将能够看到哪个进程正在阻止您的文件。
您还可以在 C# 中完成此工作,请检查:什么进程锁定文件?。还

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

樱&纷飞 2024-11-18 04:51:43

尝试:

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

Try:

var sourceFile = new FileInfo(sourceFilePath);
sourceFile.CopyTo(destinationFilePath, true);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文