Stream.CopyTo 不复制任何流数据
- 作者: 師876945520
- 来源: 51数据库
- 2023-02-13
问题描述
我在将数据从 MemoryStream 复制到 ZipArchive 中的 Stream 时遇到问题.以下不起作用 - 它仅返回 114 个字节:
I'm having an issue with copying data from a MemoryStream into a Stream inside a ZipArchive. The following is NOT working - it returns only 114 bytes:
GetDataAsByteArray(IDataSource dataSource) { using (var zipStream = new MemoryStream()) { using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true)) { var file = archive.CreateEntry("compressed.file"); using (var targetStream = file.Open()) { using (var sourceStream = new MemoryStream()) { await dataSource.LoadIntoStream(sourceStream); sourceStream.CopyTo(targetStream); } } } var result = zipStream.ToArray(); zipStream.Close(); return result; } }
但是,使用下面的复制"过程实现,所有 1103 个字节都写入数组/内存流:
However, using the implementation below for the "copy"-process, all 1103 bytes are written to the array/memory stream:
await targetStream.WriteAsync(sourceStream.ToArray(), 0, (int) sourceStream.Length);
我想知道为什么 CopyTo 产生更少的字节.此外,我对在第二个实现中转换为 Int32 感到不安全.
I'm wondering why the CopyTo yields less bytes. Also I'm feeling unsecure with the cast to Int32 in the second implementation.
仅供参考: 比较字节数组:看起来第一个实现只编写了 zip 文件的页眉和页脚.
FYI: Comparing the byte array: It looks like only the header and footer of the zip file were written by the first implementation.
推荐答案
Stream.CopyTo() 从流的当前位置开始复制.在 LoadIntoStream() 调用之后,它可能不是 0.由于它是一个 MemoryStream,你可以简单地像这样修复它:
Stream.CopyTo() starts copying from the stream's current Position. Which probably isn't 0 after that LoadIntoStream() call. Since it is a MemoryStream, you can simply fix it like this:
await dataSource.LoadIntoStream(sourceStream); sourceStream.Position = 0; sourceStream.CopyTo(targetStream);
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源









