如何合并两个内存流?

时间:2013-03-27 09:13:56

标签: c# .net memorystream

我有两个MemoryStream实例。

如何将它们合并到一个实例中?

好吧,现在我无法从一个MemoryStream复制到另一个。 这是一种方法:

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

3 个答案:

答案 0 :(得分:41)

使用CopyToCopyToAsync非常轻松:

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

框架,人。 框架

答案 1 :(得分:3)

基于上面@Will分享的答案,这里有完整的代码:

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

将流集合与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;
    }
}

答案 2 :(得分:1)

  • 使用长度创建第三个(让它为mergedStreamMemoryStream 等于第一和第二长度之和

  • 首先将MemoryStream写入mergedStream(使用GetBuffer()即可 从byte[]

  • 获取MemoryStream
  • 将第二个MemoryStream写入mergedStream(使用GetBuffer()

  • 记住写作时的偏移。

相当 附加 ,但是目前还不清楚MemoryStreams上的合并操作是什么