How to merge two memory streams?

孤者浪人 提交于 2019-12-06 22:14:05

问题


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;
    }

回答1:


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.




回答2:


Based on the answer shared by @Will above, here is complete code:

void Main()
{
    var s1 = GetStreamFromString("Hello");
    var s2 = GetStreamFromString(" World");

    var s3 = s1.Append(s2);
    Console.WriteLine(Encoding.UTF8.GetString((s3 as MemoryStream).ToArray()));
}

public static Stream GetStreamFromString(string text)
{
        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(text);
        writer.Flush();
        stream.Position = 0;

        return stream;
}

public static class Extensions
{ 
    public static Stream Append(this Stream destination, Stream source)
    {
        destination.Position = destination.Length;
        source.CopyTo(destination);

        return destination;
    }
}

And merging stream collection with async:

async Task Main()
{
    var list = new List<Task<Stream>> { GetStreamFromStringAsync("Hello"), GetStreamFromStringAsync(" World") };

    Stream stream = await list
            .Select(async item => await item)
            .Aggregate((current, next) => Task.FromResult(current.Result.Append(next.Result)));

    Console.WriteLine(Encoding.UTF8.GetString((stream as MemoryStream).ToArray()));
}

public static Task<Stream> GetStreamFromStringAsync(string text)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(text);
    writer.Flush();
    stream.Position = 0;

    return Task.FromResult(stream as Stream);
}

public static class Extensions
{
    public static Stream Append(this Stream destination, Stream source)
    {
        destination.Position = destination.Length;
        source.CopyTo(destination);

        return destination;
    }
}



回答3:


  • Create third(let it be mergedStream) MemoryStream with length equal to sum of first and second lengths

  • Write first MemoryStream to mergedStream (use GetBuffer() to get byte[] from MemoryStream)

  • Write second MemoryStream to mergedStream(use GetBuffer())

  • Remember about offset while writing.

It's rather append, but it's totally unclear what is merge operation on MemoryStreams



来源:https://stackoverflow.com/questions/15655210/how-to-merge-two-memory-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!