How to copy one file to many locations simultaneously

拟墨画扇 提交于 2019-12-22 07:27:07

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/11108427/how-to-copy-one-file-to-many-locations-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!