How to merge two memory streams?
.net, c#, memorystream
Solution
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.
Problem
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; } ```