问题描述
我在将数据从 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 不复制任何流数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!