如何合并两个内存流? [英] How to merge two memory streams?

查看:220
本文介绍了如何合并两个内存流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个MemoryStream的实例。

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

好了,现在我不能复制从一个的MemoryStream到另一个。 这里有一个方法:

 公共静态流ZipFiles(IEnumerable的< FileToZip> filesToZip){
ZipStorer斯托勒= NULL;
        MemoryStream的结果= NULL;
        尝试 {
            MemoryStream的内存=新的MemoryStream(1024);
            斯托勒= ZipStorer.Create(存储器,GetDateTimeInRuFormat());
            的foreach(在filesToZip VAR currentFilePath){
                字符串文件名= Path.GetFileName(currentFilePath.FullPath);
                storer.AddFile(ZipStorer.Com pression.Deflate,currentFilePath.FullPath,文件名,
                               GetDateTimeInRuFormat());
            }
            结果=新的MemoryStream((INT)storer.ZipFileStream.Length);
            storer.ZipFileStream.CopyTo(结果); //不行的!
                                               //结果的长度将是零
        }
        赶上(例外){
        }
        最后 {
            如果(斯托勒!= NULL)
                storer.Close();
        }
        返回结果;
    }
 

解决方案

与壮观容易 CopyTo从 CopyToAsync

  VAR streamOne =新的MemoryStream();
FillThisStreamUp(streamOne);
VAR streamTwo =新的MemoryStream();
DoSomethingToThisStreamLol(streamTwo);
streamTwo.CopyTo(streamOne); // streamOne保持两者的内容
 

该框架,人。在框架的。

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

解决方案

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.

这篇关于如何合并两个内存流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆