How to merge two memory streams?

SaneDeveloper picture SaneDeveloper · Mar 27, 2013 · Viewed 28.2k times · Source

I have two MemoryStream instances.

How to merge them into one instance?

Well, now I can't copy from one MemoryStream to another. Here is a method:

public static Stream ZipFiles(IEnumerable<FileToZip> filesToZip) {
ZipStorer storer = null;
        MemoryStream result = null;
        try {
            MemoryStream memory = new MemoryStream(1024);
            storer = ZipStorer.Create(memory, GetDateTimeInRuFormat());
            foreach (var currentFilePath in filesToZip) {
                string fileName = Path.GetFileName(currentFilePath.FullPath);
                storer.AddFile(ZipStorer.Compression.Deflate, currentFilePath.FullPath, fileName,
                               GetDateTimeInRuFormat());
            }
            result = new MemoryStream((int) storer.ZipFileStream.Length);
            storer.ZipFileStream.CopyTo(result); //Does not work! 
                                               //result's length will be zero
        }
        catch (Exception) {
        }
        finally {
            if (storer != null)
                storer.Close();
        }
        return result;
    }

Answer

user1228 picture user1228 · Mar 27, 2013

Spectacularly easy with CopyTo or CopyToAsync:

var streamOne = new MemoryStream();
FillThisStreamUp(streamOne);
var streamTwo = new MemoryStream();
DoSomethingToThisStreamLol(streamTwo);
streamTwo.CopyTo(streamOne); // streamOne holds the contents of both

The framework, people. The framework.