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 不复制任何流数据
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
