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

its*_*sho 5 c# file-io memorystream copy file-copying

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

意味着我不希望原始文件只被读取一次,并将文件"粘贴"到另一个位置(在本地网络上).

就我的测试给我看的那样

File.Copy() 
Run Code Online (Sandbox Code Playgroud)

将永远再次阅读来源.

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

所以基本上,我想模仿"复制 - 粘贴"形式的一个"复制"和多个"粘贴",而无需再次从硬盘驱动器重新读取.

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

那么,甚至可以实现吗?

Hac*_*ese 9

而不是使用File.Copy工具方法,你可以打开源文件作为FileStream,然后尽可能多的打开FileStreams你需要然而,许多目标文件,从源中读取和写入每个目标流.

更新将其更改为使用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);
                                     }
                                 }

                             });
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

FileUtil.CopyMultiple(@"C:\sourceFile1.txt", @"C:\destination1\sourcefile1.txt", @"C:\destination2\sourcefile1.txt");
Run Code Online (Sandbox Code Playgroud)

  • 如果我今天正在回答这个问题,我可能会使用Reactive Extensions来订阅流,无论你需要多少副本,都是异步编写的. (3认同)