I do not believe in .NET to allow copying a section of a file without buffering it in memory. However, it seems to me that this is still inefficient, since he needs to open the input file and search for it many times. If you just split the file, why not open the input file once, and then just write something like:
public static void CopySection(Stream input, string targetFile, int length) { byte[] buffer = new byte[8192]; using (Stream output = File.OpenWrite(targetFile)) { int bytesRead = 1;
This has slight inefficiency when creating a buffer for each call - you may want to create a buffer once and pass it to the method:
public static void CopySection(Stream input, string targetFile, int length, byte[] buffer) { using (Stream output = File.OpenWrite(targetFile)) { int bytesRead = 1;
Note that this also closes the output stream (due to the using statement) that your source code did not have.
The important point is that it will use the operating system file buffering more efficiently, since you are reusing the same input stream, instead of reopening the file at the beginning and then searching.
I think it will be much faster, but obviously you need to try to see ...
This involves adjacent pieces, of course. If you need to skip bits of a file, you can do this outside the method. In addition, if you write very small files, you can also optimize this situation - the easiest way to do this is to introduce a BufferedStream wrapping the input stream.
Jon Skeet Jun 05 '09 at 13:49 2009-06-05 13:49
source share