Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unzip a zip file c#

Tags:

c#

winforms

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.

like image 540
Sharrok G Avatar asked Nov 20 '11 11:11

Sharrok G


1 Answers

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.

like image 80
gideon Avatar answered Nov 14 '22 01:11

gideon