如何在foreach循环中追加到memoryStream而不覆盖其内容?

时间:2019-01-29 22:56:37

标签: c# stream memorystream

我目前正在进行API调用,以返回MemoryStream对象。我在遍历for循环并使用copyTo方法将内存流附加到另一个时遇到问题。它会覆盖流中已有的内容。

到目前为止,我已经尝试了几乎所有堆栈溢出答案的组合,但未能获得正确的结果。

                MemoryStream docStream2 = new MemoryStream();
                MemoryStream docStream3 = new MemoryStream();

                docStream = (MemoryStream)ApiCall
                docStream2 = (MemoryStream)ApiCall
                docStream3 = (MemoryStream)ApiCall

                docStream.Position = 0;
                docStream2.Position = 0;
                docStream2.CopyTo(docStream);
                docStream.Position = docStream.Length;
                docStream3.Position = 0;
                docStream3.CopyTo(docStream);

                return docStream

我期望获得一个包含每个docStream memoryStream对象的所有内容的流。相反,我只得到最后一个流。我也考虑过要制作一个流列表,但是我还没有找到一种将流列表从webapi2返回到mvc4应用程序的方法,但这是一个附带问题。预先感谢!

1 个答案:

答案 0 :(得分:1)

Id使用WriteTo,因为您不必担心阅读流的位置

知道这一点,您需要做的就是确保结果流的位置在您想要的位置(结尾)

考虑此测试应用

// Create some data
var stuff = Enumerable.Range(0, 15)
                        .Select(x => (byte)x)
                        .ToArray();

// Create some streams
var ms1 = new MemoryStream();
var ms2 = new MemoryStream();
var ms3 = new MemoryStream();

// write some data to the streams for a test
ms1.Write(stuff, 0, 5);
ms2.Write(stuff, 5, 5);
ms3.Write(stuff, 10, 5);

// make sure we are at the end of the result stream
ms1.Seek(0, SeekOrigin.End);

// write the other streams to the result
ms2.WriteTo(ms1);
ms3.WriteTo(ms1);

// test its working
Console.WriteLine(string.Join(", ", ms1.ToArray()));

输出

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