Unzip files programmatically in .net
Solution 1
We have used SharpZipLib successfully on many projects. I know it's a third party tool, but source code is included and could provide some insight if you chose to reinvent the wheel here.
Solution 2
With .NET 4.5 you can now unzip files using the .NET framework:
using System;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath);
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
The above code was taken directly from Microsoft's documentation: http://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx
ZipFile
is contained in the assembly System.IO.Compression.FileSystem
. (Thanks nateirvin...see comment below). You need to add a DLL reference to the framework assembly System.IO.Compression.FileSystem.dll
Solution 3
For .Net 4.5+
It is not always desired to write the uncompressed file to disk. As an ASP.Net developer, I would have to fiddle with permissions to grant rights for my application to write to the filesystem. By working with streams in memory, I can sidestep all that and read the files directly:
using (ZipArchive archive = new ZipArchive(postedZipStream))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
var stream = entry.Open();
//Do awesome stream stuff!!
}
}
Alternatively, you can still write the decompressed file out to disk by calling ExtractToFile()
:
using (ZipArchive archive = ZipFile.OpenRead(pathToZip))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
entry.ExtractToFile(Path.Combine(destination, entry.FullName));
}
}
To use the ZipArchive
class, you will need to add a reference to the System.IO.Compression
namespace and to System.IO.Compression.FileSystem
.
Solution 4
Free, and no external DLL files. Everything is in one CS file. One download is just the CS file, another download is a very easy to understand example. Just tried it today and I can't believe how simple the setup was. It worked on first try, no errors, no nothing.
https://github.com/jaime-olivares/zipstorer
Solution 5
Use the DotNetZip library at http://www.codeplex.com/DotNetZip
class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...
DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...
If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...
Related videos on Youtube
Petteri
Updated on November 05, 2021Comments
-
Petteri over 2 years
I am trying to programatically unzip a zipped file.
I have tried using the
System.IO.Compression.GZipStream
class in .NET, but when my app runs (actually a unit test) I get this exception:System.IO.InvalidDataException: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream..
I now realize that a
.zip
file is not the same as a.gz
file, and thatGZip
is not the same asZip
.However, since I'm able to extract the file by manually double clicking the zipped file and then clicking the "Extract all files"-button, I think there should be a way of doing that in code as well.
Therefore I've tried to use
Process.Start()
with the path to the zipped file as input. This causes my app to open a Window showing the contents in the zipped file. That's all fine, but the app will be installed on a server with none around to click the "Extract all files"-button.So, how do I get my app to extract the files in the zipped files?
Or is there another way to do it? I prefer doing it in code, without downloading any third party libraries or apps; the security department ain't too fancy about that...
-
Jared Updike about 15 yearsYour security department is happier with you writing your own code for something than using a library that has been debugged and looked at by presumably many eyes? You can use a library AND "do it in code" (get the source and compile it yourself) but I see reinventing the wheel as a bigger problem than any security issues brought about by using a tried and true library.
-
Nate Cook3 about 15 years@Jared - When management gets an idea in their head...
-
Simon about 15 yearsThere is less risk for security department if you get a third party product. Just download dotnetzip and rename it "[insert company name].ziplibrary.dll"
-
-
Petteri about 15 yearsI'm trying out the DeflateStream class. This time I get System.IO.InvalidDataException: Block length does not match with its complement..
-
Petteri about 15 yearsHmmm... But that's a third party library!
-
Kenneth Cochran about 15 yearsAs I said above, Microsoft only provided the algorithm. You'll need info on the zip archive format as well. en.wikipedia.org/wiki/ZIP_(file_format) should get you started. See the references at the bottom of the page for links to more detailed info.
-
Kenneth Cochran about 15 yearsI also stumbled acrossed System.IO.Packaging.Package in .NET 3.5. It looks like it may do the trick though its not very intuitive.
-
Sam Axe about 15 yearsHow very observant of you. Unless you feel like spending several months implemening your own Zip file reader, its your best option.
-
RolandTumble about 15 yearsI don't know about your company, but my experience has always been that it's possible to get an exception to that sort of rule if you write up a business case description of why you want the exception. Point out the cost savings v. DIY, as well as the fact that the source can be examined. As a fallback, you can often get permission to use the source even if they won't let you use the dll--then just compile it yourself (or at least the parts you actually need to use...).
-
nateirvin over 11 yearsBTW,
ZipFile
is contained in the assemblySystem.IO.Compression.FileSystem
. -
Chris Schiffhauer almost 11 yearsWhich means that you need to add a DLL reference to the framework assembly
System.IO.Compression.FileSystem.dll
. -
Kugel over 10 yearsThis one is way better than SharpZipLib
-
Mikael Dúi Bolinder about 10 years@Dan-o Why not Microsoft Compression? nuget.org/packages/Microsoft.Bcl.Compression
-
oyophant about 10 yearsSpoke too soon! I want to inflate the files from an http download stream instantly. This does not work since it is using Seek operations on the stream :( Well, thanks to the source code I can write my own ZipStream now...
-
Sam Axe about 10 yearsYour're asking me questions about an answer that is nearly 5 years old. Do some research. I'm sure you will find an answer.
-
Thronk over 9 yearsThis requires dot net 4.5 - just a note as others who answered with ZipFile noted and I am still using 3.5.
-
JWP almost 9 yearsDid it really take MSFT until 4.5+ to add a native decompressor?
-
Mister Epic almost 9 years@JohnPeters GZipStream was added back in .Net 2.0 (msdn.microsoft.com/en-us/library/…). However, it didn't make it easy to work with multiple files in an archive in memory. The new
ZipArchive
object fits the bill nicely. -
ANeves over 8 yearsThis is a particularly good alternative because it allows unzipping without using the file-system (in my case I am working with embedded resources), and it's also not a third-party extension.
-
Niklas almost 8 yearsthe best solution to my problem,since im writing an updater app and i cant involve any DLLs in the extraction process since then i would have to update those too....this is good.thank you !
-
Phil Cooper about 7 years@Kugel this is not a dig, but how in your opinion is it better? I'm considering changing over but gathering knowledge before I do?
-
Kugel about 7 years@PhilCooper This is a very old question I recommend using the built-in System.IO.Compression.ZipFile. IIRC I had really bad experiences with SharpZipLib in the past based on my experience of producing thousands of zips on the fly.
-
Phil Cooper about 7 years@Kugel appreciate your response, I'll give it a try.
-
arturn about 7 yearsYou don't have to use external libraries to uncompress zip files, you could use Shell32 from System32. Please see stackoverflow.com/a/43066281/948694
-
Raghu about 7 yearswhat about .rar files. above code fails to extract .rar files.
-
SoftSan almost 7 yearsI tried this in my asp.net core web api, it read first entry fine, but on second entry it always give error
A local file header is corrupt
. Any though on this? -
SoftSan almost 7 yearsI tried this in my asp.net core web api, it read first entry fine, but on second entry it always give error
A local file header is corrupt
. Any though on this? -
The Fluffy Robot almost 7 yearsWhy should I use a
foreach
loop toExtractToFile
when I can just useZipFile.ExtractToDirectory(inputFile, outputDir);
What is the advantage of the first method? -
gkubed over 6 years
-
Ravi Anand over 6 yearsin .NET 4.6.1 i am not able to get 'ZipArchive' from 'System.IO.Compression.FileSystem', any Idea?
-
mrid about 6 yearsdoesn't work if i concatenate a zip file to another file ( say for example
copy \b file1.mp3 + file2.zip file1.mp3
) -
Rich almost 6 yearsSame with @SoftSan. I got also that error. What to do?
-
Kyle almost 6 yearsThis is great for anyone working on .net standard / core and needs to uncompress a stream instead of a file, as the main nuget packages for working with zip files are not .net standard.
-
nonzaprej almost 6 yearsI had the error
'ZipArchiveEntry' does not contain a definition for 'ExtractToFile'
and I found out that, instead, I have to use the static methodSystem.IO.Compression.ZipFileExtensions.ExtractToFile
. -
Kairan over 5 yearsI imported System.IO.Compression, but received this error on build: Error 1 The type or namespace name 'ZipArchive' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Josh\Desktop\delete\WindowsFormsApplication2\WindowsFormsApplication2\Form1.cs 45 25 WindowsFormsApplication2
-
Aidan over 5 yearsThis does not preserve file permissions on unix based systems, so I'd suggest not using it if you need to work on Macs or Linux.
-
bsara about 5 years@Aidan that's good to know, though, it would be a good recommendation to not use .NET on Mac/Linux if at all possible. Where it isn't, this is helpful. Thanks.
-
Glebka almost 3 yearsCode example: stackoverflow.com/a/22444096/273455
-
Chandraprakash over 2 yearsAt 2021, you can directly install the Sytem.IO.Compression NuGet package from package manager rather than attaching the dll manually in reference.