Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy one file to many locations simultaneously

I want to find a way to copy one file to multiple locations simultaneously (with C#).

means that i don't want the original file to be read only one time, and to "paste" the file to another locations (on local network).

as far as my tests showed me, the

File.Copy() 

will always read the source again.

and as far as i understand, even while using memory, that memory piece gets locked.

so basically, i want to mimic the "copy-paste" to the form of one "copy", and multiple "paste", without re-reading from the Hard Drive again.

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

So, Is it even possible to achieve ?

like image 498
itsho Avatar asked Jun 19 '12 19:06

itsho


1 Answers

Rather than using the File.Copy utility method, you could open the source file as a FileStream, then open as many FileStreams to however many destination files you need, read from the source, and write to each destination stream.

UPDATE Changed it to write files using Parallel.ForEach to improve 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);
                                     }
                                 }

                             });
    }
}

Usage:

FileUtil.CopyMultiple(@"C:\sourceFile1.txt", @"C:\destination1\sourcefile1.txt", @"C:\destination2\sourcefile1.txt");
like image 193
moribvndvs Avatar answered Sep 28 '22 04:09

moribvndvs