This example copies all the alternate data streams in a file to individual files in a target directory using the AsyncStream and AlternateStreams classes.
The main purpose here is to demonstrate how asynchronous I/O can improve performance when multiple streams are being used simultaneously. Assuming that the source and target files are on different disks of equal speed and discounting the effect of caching, the time required to copy each stream is cut in half: instead of waiting for data to be read and then waiting for it to be written with synchronous FileStream I/O, the AsyncStreams read and write at the same time. Notice that this gain is realized simply by wrapping the two original FileStreams in AsyncStreams.
using System; using System.IO; using BetterStreams; namespace BetterStreamsExamples { static class CopyExample { public static void CopyADS(string filename, string targetDirectory) { //get a list of all the alternate data streams in the file long[] streamLengths; string[] streamNames = AlternateStreams.GetStreamNames(filename, out streamLengths); //4KB buffer used to transfer data byte[] buffer = new byte[4096]; //copy each stream's contents into a new file //(an exception will be thrown if any target files already exist) for (int i = 0; i < streamNames.Length; i++) { string targetFile = Path.Combine(targetDirectory, streamNames[i]); AsyncStream source = new AsyncStream ( AlternateStreams.OpenStream(filename, streamNames[i]), AsyncStreamMode.Reading, 1024 * 50 //50KB buffer ); AsyncStream target = new AsyncStream ( new FileStream(targetFile, FileMode.CreateNew), AsyncStreamMode.Writing, 1024 * 50 //50KB buffer ); target.SetLength(streamLengths[i]); //copy int readBytes; while ((readBytes = source.Read(buffer, 0, buffer.Length)) > 0) target.Write(buffer, 0, readBytes); source.Close(); target.Close(); } } } } |