Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DeflateStream CopyTo MemoryStream_C#_Memorystream_Deflate - Fatal编程技术网

C# DeflateStream CopyTo MemoryStream

C# DeflateStream CopyTo MemoryStream,c#,memorystream,deflate,C#,Memorystream,Deflate,正在压缩和解压缩MemoryStream,但CopyTo似乎无法正常工作?为什么?如何解决这个问题 public static MemoryStream Compress(MemoryStream originalStream) { Console.WriteLine("Original before compressing size: {0}", originalStream.Length.ToString()); MemoryStream compressedMemorySt

正在压缩和解压缩
MemoryStream
,但
CopyTo
似乎无法正常工作?为什么?如何解决这个问题

public static MemoryStream Compress(MemoryStream originalStream)
{
    Console.WriteLine("Original before compressing size: {0}", originalStream.Length.ToString());
    MemoryStream compressedMemoryStream = new MemoryStream();

    using (DeflateStream deflateStream = new DeflateStream(compressedMemoryStream, CompressionMode.Compress, true))
    {
        originalStream.CopyTo(deflateStream);
    }
    Console.WriteLine("Compressed size: {0}", compressedMemoryStream.Length.ToString());
    return compressedMemoryStream;
}

public static void Decompress(MemoryStream compressedStream)
{
    Console.WriteLine("Compressed before decompressing size: {0}", compressedStream.Length.ToString());
    using (MemoryStream decompressedFileStream = new MemoryStream())
    {
         using (DeflateStream decompressionStream = new DeflateStream(compressedStream, CompressionMode.Decompress, true))
         {
              decompressionStream.CopyTo(decompressedFileStream);
         }
         Console.WriteLine("Decompressed size: {0}", decompressedFileStream.Length.ToString());
    }
}
输出:

Original before compressing size: 5184054
Compressed size: 0
Compressed before decompressing size: 0
Decompressed size: 0

CopyTo
开始从源流的当前位置复制字节

由于您发布的结果压缩流大小为0,我非常确定
originalStream
位于流的末尾,因此没有复制/压缩字节

确保位置为
0
,以便它可以找到要复制并压缩到流中的任何数据


正如@xanatos所提到的,这同样适用于
解压缩
,因此在解压缩之前,请确保
压缩流
也位于0。

在开始复制之前,请确保原始流位于
位置=0
。否则它将找不到任何要复制的内容,因为它位于流的末尾(因为您以前向它写入了数据?)。@RayKoopa,是的,您是对的!贴上答案我会接受的@A191919,记住将新的
内存流compressedMemoryStream
移动到末尾的
位置=0