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 不复制任何流数据
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01