c# - 如何合并两个内存流?

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

最佳答案

使用 CopyTo 非常简单或 CopyToAsync :

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

框架,人。 框架

关于c# - 如何合并两个内存流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15655210/

相关文章:

c# - 将 DTO 传递给我的 ViewModels 构造函数以映射属性

c# - BinaryWriter 不寻常的十六进制

c# - 从 ConnectStream 异步写入 MemoryStream

c# - 以对数方式记录 1、10、100、1000 等

c# - 等效于 c# 中的 unsigned char *

c# - 重新生成 Microsoft PowerShell 存储库测试项目以安装并在 C# .net6 中运行 AZ PowerShell SDK

c# - Winform 出现 Red X 异常

c# - 依赖注入(inject) : How to pass the injection container around?

c# - StreamWriter 写入 MemoryStream

c# - 如何断言代码正在主线程中运行?