Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split (copy) a Stream in .NET?

Tags:

c#

.net

io

stream

Does anyone know where I can find a Stream splitter implementation?

I'm looking to take a Stream, and obtain two separate streams that can be independently read and closed without impacting each other. These streams should each return the same binary data that the original stream would. No need to implement Position or Seek and such... Forward only.

I'd prefer if it didn't just copy the whole stream into memory and serve it up multiple times, which would be fairly simple enough to implement myself.

Is there anything out there that could do this?

like image 200
TheSoftwareJedi Avatar asked Jun 28 '09 21:06

TheSoftwareJedi


1 Answers

I have made a SplitStream available on github and NuGet.

It goes like this.

using (var inputSplitStream = new ReadableSplitStream(inputSourceStream))

using (var inputFileStream = inputSplitStream.GetForwardReadOnlyStream())
using (var outputFileStream = File.OpenWrite("MyFileOnAnyFilestore.bin"))

using (var inputSha1Stream = inputSplitStream.GetForwardReadOnlyStream())
using (var outputSha1Stream = SHA1.Create())
{
    inputSplitStream.StartReadAhead();

    Parallel.Invoke(
        () => {
            var bytes = outputSha1Stream.ComputeHash(inputSha1Stream);
            var checksumSha1 = string.Join("", bytes.Select(x => x.ToString("x")));
        },
        () => {
            inputFileStream.CopyTo(outputFileStream);
        },
    );
}

I have not tested it on very large streams, but give it a try.

github: https://github.com/microknights/SplitStream

like image 117
Frank Nielsen Avatar answered Sep 18 '22 15:09

Frank Nielsen