如何同时将一个文件复制到多个位置

时间:2012-06-19 19:57:29

标签: c# file-io copy memorystream file-copying

我想找到一种方法将一个文件复制到多个位置同时(使用C#)。

表示我不希望原始文件只被读取一次,并将文件“粘贴”到另一个位置(在本地网络上)。

据我的测试显示,

File.Copy() 

将始终再次阅读来源。

据我所知,即使在使用内存时,该内存片也会被锁定。

所以基本上,我想模仿“复制 - 粘贴”形式的一个“复制”,多个“粘贴”,没有再次从硬盘重新读取。

为什么? 因为最终,我需要将一个文件夹(超过1GB)复制到许多计算机,瓶颈是我需要读取源文件的部分。

所以, 甚至可以实现吗?

1 个答案:

答案 0 :(得分:9)

您可以将源文件作为File.Copy打开,而不是使用FileStream实用程序方法,然后打开尽可能多的FileStreams到您需要的许多目标文件,从源代码中读取,并写入每个目标流。

UPDATE 将其更改为使用Parallel.ForEach写入文件以提高吞吐量。

public static class FileUtil
{
    public static void CopyMultiple(string sourceFilePath, params string[] destinationPaths)
    {
        if (string.IsNullOrEmpty(sourceFilePath)) throw new ArgumentException("A source file must be specified.", "sourceFilePath");

        if (destinationPaths == null || destinationPaths.Length == 0) throw new ArgumentException("At least one destination file must be specified.", "destinationPaths");

        Parallel.ForEach(destinationPaths, new ParallelOptions(),
                         destinationPath =>
                             {
                                 using (var source = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                 using (var destination = new FileStream(destinationPath, FileMode.Create))
                                 {
                                     var buffer = new byte[1024];
                                     int read;

                                     while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
                                     {
                                         destination.Write(buffer, 0, read);
                                     }
                                 }

                             });
    }
}

用法:

FileUtil.CopyMultiple(@"C:\sourceFile1.txt", @"C:\destination1\sourcefile1.txt", @"C:\destination2\sourcefile1.txt");