How to copy one file to many locations at once

I want to find a way to copy one file to several locations at the same time (with C #).

means that I do not want the source file to be read only once and "pasted" the file to other places (on the local network).

as my tests showed

File.Copy() 

will always read the source again.

and as I understand it, even when using memory, this part of the memory is blocked.

so basically, I want to emulate “copy-paste” as one “copy” and again “re-paste” without from the hard drive.

Why? because in the end I need to copy one folder (more than 1 GB) to many computers, and the bottleneck is the part that I need to read the source file.

So, is it even possible to achieve?

+5
source share
1 answer

Instead of using the utility method, File.Copyyou can open the source file as FileStream, and then open as much as possible FileStreamsso that you need as many destination files as you need, read from the source and write a stream to each destination.

UPDATE Modified to write files using Parallel.ForEach to increase throughput.

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

                             });
    }
}

Using:

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

All Articles