0

Hello everyone I am getting this exception:

The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.

All I have done is decompress the file into a GZip and then pass that into a stream, to pass that into a file.

using (FileStream fInStream = new FileStream(@"C:\Users\UNI\Desktop\FrostbyteDBUpdateProgram\FrostbyteDBUpdateProgram\bin\Debug\" + fileName, FileMode.Open, FileAccess.Read))
        {
            using (GZipStream gZip = new GZipStream(fInStream, CompressionMode.Decompress))
            {
                using (FileStream fOutStream = new FileStream(@"C:\Users\UNI\Desktop\FrostbyteDBUpdateProgram\FrostbyteDBUpdateProgram\bin\Debug\test1.docx", FileMode.Create, FileAccess.Write))
                {
                    byte[] tempBytes = new byte[4096];
                    int i;
                    while ((i = gZip.Read(tempBytes, 0, tempBytes.Length)) != 0)
                    {
                        fOutStream.Write(tempBytes, 0, i);
                    }
                }
                gZip.Close();
            }
            fInStream.Close();
        }
Vasa Serafin
  • 306
  • 5
  • 18
  • Q: Did you confirm the filename of the filestream you're opening is correct? Q: Did you open the file to confirm it's a valid .zip file? Q: Why "4096"? – paulsm4 Jun 30 '12 at 04:08
  • Side notes: no need to call `Close` (since you are correcly using `using`) and consider using [Stream.CopyTo](http://msdn.microsoft.com/en-us/library/dd782932.aspx) instead of manual copying stream since you can already have 4.0. – Alexei Levenkov Jun 30 '12 at 04:40
  • How would you implement the stream.copyTo? – Vasa Serafin Jun 30 '12 at 05:25

1 Answers1

3

The GZipStream class is not suitable to read compressed archives in the .gz or .zip format. It only knows how to de/compress data, it doesn't know anything about the archive file structure. Which can contain multiple files, note how the class doesn't have any way to select the specific file in the archive you want to decompress.

Zip archive support will be added in .NET 4.5. Until then you could use the popular SharpZipLib or DotNetZip libraries. Google their name to find the download.

If the file you want to decompress was actually generated by GZipStream then there's a bug in the code that did that, we can't see it.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • OK, thanks for the heads up, I will research more into it. I just wanted a sort of confirmation that those where legitimate lib's to download and use. – Vasa Serafin Jun 30 '12 at 11:49