Sharrok G
Sharrok G

Reputation: 457

How to Unzip a zip file c#

I want to Extract a zip file programatically.

I have searched google but i have not found it. I am using these code but i am getting this error

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

Code:

    public static void Decompress(FileInfo fi)
    {
        using (FileStream inFile = fi.OpenRead())
        {
            string curFile = fi.FullName;
            string origName = curFile.Remove(curFile.Length - fi.Extension.Length);
            using (FileStream outFile = File.Create(origName))
            {
                using (GZipStream Decompress = new GZipStream(inFile,
                        CompressionMode.Decompress))
                {
                    byte[] buffer = new byte[4096];
                    int numRead;
                    while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        outFile.Write(buffer, 0, numRead);
                    }
                    Console.WriteLine("Decompressed: {0}", fi.Name);

                }
            }
        }
    }

There would be great appreciation if someone could help me.

Thanks In Advance.

Upvotes: 5

Views: 2010

Answers (1)

gideon
gideon

Reputation: 19465

The error suggests you are not opening a GZip file. The GZip library cannot open standard ZIP Archives.

See GZip Format on wikipedia

You can use DotNetZip to open/read/write standard zip archives and even write encrypted, password protected zips. It's also on nuget.

Upvotes: 11

Related Questions