2010-10-20 58 views
2

我正在使用.Net GZipStream类来压缩和解压缩文件。在我进行解压缩之后,数据看起来很好,但在某个看似任意的点之后,它变成了零。例如,解压文件后,它的大小是正确的19KB,但字节10,588和全部为零。GZip解压缩停止在任意点

我不知道我在做什么不正确。

这是我该怎么办压缩:

Byte[] bytes = GetFileBytes(file); 

using (FileStream fileStream = new FileStream("Zipped.gz", FileMode.Create)) 
{ 
    using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Compress)) 
    { 
     zipStream.Write(bytes, 0, bytes.Length); 
    } 
} 

这就是我要做的减压(字节是压缩字节数组,OriginalSize是文件的大小,然后才压缩):

using (MemoryStream memoryStream = new MemoryStream(Bytes)) 
{ 
    using (GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) 
    { 
     // Note: Since the compressed version can be larger, I use the larger of the original and the compressed size for the decompressed array's size. 
     Byte[] decompressedBytes = new Byte[OriginalSize > Bytes.Length ? OriginalSize : Bytes.Length]; 

     Int32 numRead = zipStream.Read(decompressedBytes, 0, Bytes.Length); 

     using (FileStream fileStream = new FileStream("Decompressed.txt", Name), FileMode.Create)) 
     { 
      fileStream.Write(decompressedBytes, 0, Convert.ToInt32(OriginalSize)); 
     } 
    } 
} 
+0

是否知道它是否在解压缩或压缩 - 您可以通过使用gzip手动解压缩/压缩文件来检查此问题。 – 2010-10-20 00:31:57

回答

3

我在这里看到一个潜在的错误:您做出假设! :)在流之间复制时必须使用循环,请参阅this question

+0

嗯,不要:)再看看那个链接:)(你甚至可以使用那里的方法,这是最简单的) – Onkelborg 2010-10-20 00:25:12