I have a directory that contains several files. I want compress this folder to a zip or tar.gz file. How can I do his work in C#?
You can use DotNetZip Library. It has quite rich and useful features.
EDIT:
string[] MainDirs = Directory.GetDirectories(DirString);
for (int i = 0; i < MainDirs.Length; i++)
{
using (ZipFile zip = new ZipFile())
{
zip.UseUnicodeAsNecessary = true;
zip.AddDirectory(MainDirs[i]);
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
zip.Save(string.Format("test{0}.zip", i));
}
}
Look into using SharpZipLib. It supports both GZip and ZIP compression in C#.
There is an excellent tutorial here outlining what you need to do to zip a directory with SharpZipLib.
use 7zip from commandline in C# --> LZMA SDK supports C#, and there are codesamples in the package
i use the System.IO.Packaging Namespace which was introduced with .NET Framework 3.5. I decided to use that one because it's based on .NET Framework Base classes and no 3rd party code is required which blows up the size of the code..
here's another post on Stackoverflow regarding this Question
And here's the Namespace and ZipPackage declaration / explanation #MSDN
hope that helps
Christian
At my previous job we used #ziplib.
The question is quite old and so are the answers.
Best answer since end of 2012 is: Use .NET 4.5 and the contained System.IO.Compression and System.IO.Compression.ZipArchive namespace classes.
One of many example links you receive if you search in the internet:
http://www.codeproject.com/Articles/381661/Creating-Zip-Files-Easily-in-NET
Since 2014/2015 ff.:
With Roslyn the whole framework library was published as Open Source, so AFAI understand it, you are free to extract the code from the 4.5 classes (as it should be not really system specific) and use it as a library for the earlier .NET frameworks. Maybe this would give some license advantages over using the other classes- but this has to be analyzed by you.
This is a good discussion that discusses the possibility of doing this without any third party libraries. I think you should have a look on it.
Here is a large repository of sample codes that can help you in your work. Good Luck..
GZip is part of Microsoft Framework 2.0 onward.
Its called GZipStream under System.IO.Compression namespace.
To compress a directory with this class, you'd have to create a serializable class (for e.g. Directory) which contains a collection of Files.
The Files class would contain file-name and file-stream to read bytes from file.
Once you do apply GZip on the Directory, it'll read Files one by one and write them to GZipStream.
Check this link: http://www.vwd-cms.com/forum/forums.aspx?topic=18
Another pre-3.5 option is to use the zip utilities from J#. After all, .Net doesn't care what language the code was originally written in ;-).
Articles on how to do this:
ASP-Alliance
MSDN
CodeProject
C-Sharp Corner
You can zip the directory in pure .NET 3.0.
First, you will need a reference to WindowsBase.dll.
This code will open or create a zip file, create a directory inside, and place the file in that directory. If you want to zip a folder, possibly containing sub-directories, you could loop through the files in the directory and call this method for each file. Then, you could depth-first search the sub-directories for files, call the method for each of those and pass in the path to create that hierarchy within the zip file.
public void AddFileToZip(string zipFilename, string fileToAdd, string destDir)
{
using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
{
string destFilename = "." + destDir + "\\" + Path.GetFileName(fileToAdd);
Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
if (zip.PartExists(uri))
{
zip.DeletePart(uri);
}
PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
{
using (Stream dest = part.GetStream())
{
CopyStream(fileStream, dest);
}
}
}
}
destDir could be an empty string, which would place the file directly in the zip.
Sources:
https://weblogs.asp.net/jongalloway/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib
https://weblogs.asp.net/albertpascual/creating-a-folder-inside-the-zip-file-with-system-io-packaging
The most simple solution that I found using System.IO.Compression available from .Net 4.0:
System.IO.Compression.ZipFile.CreateFromDirectory(directoryToArchivePath, archiveDestinationPath);
Related
I have a question according to the ZipArchive Library in System.IO.Compression.
I want to create an uncompressed .zip file. My code so far looks like this:
//Creates a "Deflate"-Mode file in the created zip.
using (FileStream fs = new FileStream(zippath, FileMode.OpenOrCreate))
using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Update))
{
var demoFile = zip.CreateEntry("foo0.txt", CompressionLevel.NoCompression); //NoCompression does not seem to have an impact
using (var streamWriter = new StreamWriter(demoFile.Open()))
{
streamWriter.Write("Bar!");
}
}
Thats creating me a zip file, where the file in it was written in "DEFLATE" Mode not in STORE. How can I fix this. My thought was, my problem would be solved by using the CompressionLevel.NoCompression.
Also writing the file to the filesystem and zipping the directory is not an option, because i want to create a zipfile with potentially hundred of thousands small files. Furthermore just using GZipStream is not an option, because I want to create a directory structure in the .zip file.
I checked the mode with 7-zip:
(screenshot from 7-zip)
If for whatever reason you are required to add contents to a ZIP file with its compression method explicitly set to STORE (no compression), you will need to use some third party library.
The .NET classes in System.IO.Compression use DEFLATE by default. There is no apparent way to change this and use another compression method or algorithm.
Providing CompressionLevel.NoCompression just tells the DEFLATE algorithm to work with the lowest compression rate1. In terms of file size, this will probably give you roughly the same end result, anyway.
Third party libraries supporting the method STORE include:
SharpCompress
(see supported formats)
SharpZipLib
(see compression methods)
DotNetZip
1 which should be... no compression. See DEFLATE's non-compressed blocks
For anyone who happens to see this topic later on, I would highly recommend the ZipStorer class by Jaime Olivares:
https://github.com/jaime-olivares/zipstorer
It's easy to add this code to a C# project (not a DLL), and it's easy to add files using 'store' instead of 'deflate'.
I need to compress a file as 7zip using SharpCompress: http://sharpcompress.codeplex.com
what I have done as follows:
using (var archive = ZipArchive.Create())
{
archive.AddEntry("CompressionTest.pdb", new FileInfo("CompressionTest.pdb"));
using (Stream newStream = File.Create("CompressionTest212.7z"))
{
archive.SaveTo(newStream, SharpCompress.Common.CompressionType.LZMA);
}
}
The compression process is done successfully. However, the compressed file can not be extracted either using 7z (http://www.7-zip.org/download.html) or winrar.
I dont know if somebody also got the same problem and had an idea how to solve it?
Thanks in advance.
I'm the author of SharpCompress (thanks for trying it out by the way) and 7Zip compression isn't supported: http://sharpcompress.codeplex.com/wikipage?title=Supported%20formats
What you wrote is code for creating a standard Zip file with LZMA compression. It's possible my code does not create a proper zip file but it's also possible that the created file can't be read by all programs. The Zip format allows for LZMA compression but not all programs may expect it. PeaZip (based on the 7Zip archiver code) does extract a Zip with LZMA, but WinRAR does not.
If you really need the 7Zip format, I do suggest using something else. Personally, I think the 7Zip format is overly complex and recommend Zip or Tar then just pick your compression of choice.
SharpCompress doesn't support 7zip compression. Only decompression, see: http://sharpcompress.codeplex.com/ ( Supported Format Table )
You can use the native library of 7zip for compression, or use an opensource wrapper around it like: http://sevenzipsharp.codeplex.com/
I need to create spanned (multi-volume) zip files using .Net, but I have been unable to find a library that enables me to do it.
Spanned zip is a zip compressed file that is split among a number of files, which usually have extensions like .z00, .z01, and so on.
The library would have to be open-source or free, because I'm gonna use it for a open source project.
(it's a duplicate to this question, but there are no answers there and I'm not going for ASP specific anyway)
DotNetZip example:
int segmentsCreated ;
using (ZipFile zip = new ZipFile())
{
zip.UseUnicode= true; // utf-8
zip.AddDirectory(#"MyDocuments\ProjectX");
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ;
zip.MaxOutputSegmentSize = 100*1024 ; // 100k segments
zip.Save("MyFiles.zip");
segmentsCreated = zip.NumberOfSegmentsForMostRecentSave ;
}
if segmentsCreated comes back as 5, then you have the following files, each not more than 100kb in size.
MyFiles.zip
MyFiles.z01
MyFiles.z02
MyFiles.z03
MyFiles.z04
Edited To Note: DotNetZip used to live at Codeplex. Codeplex has been shut down. The old archive is still [available at Codeplex][1]. It looks like the code has migrated to Github:
https://github.com/DinoChiesa/DotNetZip. Looks to be the original author's repo.
https://github.com/haf/DotNetZip.Semverd. This looks to be the currently maintained version. It's also packaged up an available via Nuget at https://www.nuget.org/packages/DotNetZip/
DotNetZip allows you to do this. From their documentation:
The library supports zip passwords, Unicode, ZIP64, stream input and output,
AES encryption, multiple compression levels, self-extracting archives,
spanned archives, and more.
Take a look at the SevenZipSharp library. It supports multivolumes archives.
As we all know .epub is a collection of files. Does anyone have an idea how can we read all that files embed in .epub runtime using C#?
The ePub specification supports two formats, a collection of files or a package of files. Most epub's use the packaging. The package is simply a ZIP file with a renamed extension.
The specification can be found here. The OEBPS Container wraps around an ePub version of the Open Packaging Format.
The simplest way to read the content is to unzip the files and look at the xhtml files that were embedded within it.
It is a zip file so how about using the Compression namespace to read the contents. Haven't use it but I'm sure this namespace exposes classes to read zip files as a stream.
I found EPUB Sharp. Unfortunately, not released yet.
http://epubsharp.sourceforge.net/
You have to use the gitden reader or you can use iBook if you are using iOS.
Free online ePub reader focusing on the social aspects of reading. Now closed, but the concept has moved to: http://www.readups.com/ per: http://www.bookglutton.com/
Source: Wikipedia
Supports EPUB 2 and EPUB 3. Books not readable directly on computers other than Macs.
How can i download a zipped folder from a remote server and unzip the entire files in the folder and store them in isolated storage space from a silver light 3 or 4 out of browser application. Any suggestion please
You can download a zip file like any files with the Webclient class, look at the details and examples in the msdn documentation for downloading content on demand it even talks about how to download and get a specific file from a zip archive.
However if you want to list the files, check out this blogpost, I've not actually tried it but it shows how to get all the files in a zip archive.
Edit: I also found this discussion which offers some ideas, it among other things mentions this Small unzip utility for Silverlight, which seems a bit more robust.
Then use the IsolatedStorageFile class to save the files.
Good Luck!
Ola
For the (un)zipping I'd highly recommend that you use the open source DotNetZip library. DotNetZip is licensed under the Ms-PL and really easy to use.
Zipping for example is easy too:
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("MyFileName.png", null, pngStream);
// Save to stream from SaveFileDialog
zip.Save(stream);
}
Silverlight SharpZipLib is a full Silverlight 3/4 and Phone7 port, less AES encryption, of SharpZipLib.
The salient limitation is one that you will find in all Silverlight compression: Only UTF8 encoding of entry meta is supported.
you could get the file using http or frp stream and then use GZipStream (.NET Class) for unziping the stream/file.
GzipStream:
http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx
Cheers
--Jocke