Stream.CopyTo not copying any stream data(Stream.CopyTo 不复制任何流数据)
问题描述
我在将数据从 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);
这篇关于Stream.CopyTo 不复制任何流数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Stream.CopyTo 不复制任何流数据
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01