Search code examples
c#memorystream

IEnumerable<Stream> to One big Stream or MemoryStream


I have IEnumerable streams. How do I convert this to a one big MemoryStream or byte[]. I want all the Stream inside streams appended into one big Stream/MemoryStream. We are having certain performance problems by iterating over all the streams. I am looking for an optimal solution.

                    using (var ms = new MemoryStream())
                        {
                            foreach (var stream in streams)
                            {
                                stream.CopyTo(ms);
                            }
                            byteData = ms.ToArray();
                        }

Thank you


Solution

  • Just call stream.CopyTo

    Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.

    var list = new List<Stream>()
    {
       new MemoryStream(new byte[] {1, 2, 3, 4}),
       new MemoryStream(new byte[] {5, 6, 7, 8}),
       new MemoryStream(new byte[] {9, 10, 11, 12})
    };
    
    var result = new MemoryStream();
    
    foreach (var stream in list)
       stream.CopyTo(result);
    
    var array =result.ToArray();
    
    Console.WriteLine(string.Join(", ", array));
    

    Output

    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12