2010-10-20 57 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