在另一个进程正在使用文件时如何复制文件 [英] How to copy a file while it is being used by another process

查看:483
本文介绍了在另一个进程正在使用文件时如何复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

引发的异常是:


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

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?

推荐答案

示例(注意:我只是将两个google结果合并在一起,您可能必须修复一些小错误;) )

An Example (note: I just combined two google results, you may have to fix minor errors ;))

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

The important part is the FileShare.ReadWrite when opening the FileStream.

我使用类似的代码打开和读取Excel文档,而excel仍处于打开状态并阻止文件。

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

这篇关于在另一个进程正在使用文件时如何复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆