Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

C# Zip Files and/or Folders

Rate me:
Please Sign up or sign in to vote.
4.82/5 (20 votes)
7 Jul 2009CPOL2 min read 243.3K   8.9K   96   21
How to Zip files and/or folders using C#

Introduction

While you're developing C# applications, you may need to perform some specific or special operations, such as zipping files to download, or sending an e-mail with a zip file attached, or performing a backup. This article proposes a solution for you to zip files and/or folders, respecting the whole tree of a folder, without the need to buy third-party solutions.

Background

C# usually uses GZip by default, which is not exactly a zip file (it is different). So, looking up for a solution, you have two kinds of options:

  • Use third-party solutions
  • Do it by yourself 

Although there are free third-party solutions, such as...

... you may find yourself wanting to do it yourself, without these libraries, using exclusively the .NET standard libraries. This article shows the way. If you attempt to find the necessary code only on C#, you will find yourself lost. C# has code just for GZip, which is not zip. After Googling (a lot!), I've been able to find a solution, which uses a mix of C# and J#. J# provides libraries specifically to zip (java.util.zip). But you may be confused about "how do I use J# on C#! Easy, just add a reference to the vjslib.dll Library (see picture below), and import the namespaces to perform the zip needed actions.

add_reference.PNG - Click to enlarge image

Using the Code

The solution is quite simple, however, it requires you to select the correct methods and specific parameters. In my sample, you have a simple Web Application with a button and a label to display the result of this process. When you press the button, a mix of C# and J# is called to zip a folder. When .NET compiles the project, it will assemble this mix as one single application. (Notice that you must have J# libraries installer on your Web server, otherwise you won't be able to have this working.)

C#
using java.io;
using java.util.zip;
using System.IO;
using System.Text;
C#
protected void btnZip_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder(); 	//  Builder to save report
        string ZipFileName = String.Format(@"C:\ZippedFolders\({0}).MyZip.zip",
		DateTime.Now.ToString("yyyyMMdd")); 	//  Zip Destiny File Name
        string theDirectory = @"C:\FolderToZip";    	//  Folder to zip

        try
        {
            sb.Append(String.Format("Directory To Zip: {0}.<br/>", theDirectory));
            sb.Append(String.Format("Zip file: {0}.<br/>", ZipFileName));

            string[] allFiles = Directory.GetFiles(theDirectory, "*.*",
		SearchOption.AllDirectories);   	// Get all files from
						// the folder to zip

            if (System.IO.File.Exists(ZipFileName)) 	//  Small piece of code
					// to delete zip file if it already exists
            {
                System.IO.File.Delete(ZipFileName);
                sb.Append(String.Format
		("Deleted old Zip file: {0}.<br/>", ZipFileName));
            }

            //  J# code to zip

            FileOutputStream fos = new FileOutputStream(ZipFileName); //  J# output
							      // stream (Zip File)
            ZipOutputStream zos = new ZipOutputStream(fos);           //  J# output zip
            zos.setLevel(9);    //  Set the level of compression.
				// It may be a value between 0 and 9

            /*
                Add each file from folder to zip, to zip file.
                This way, the tree of the folder to zip will be
                reflected on the zip file
            */

            for (int i = 0; i < allFiles.Length; i++ )
            {
                string sourceFile = allFiles[i];

                FileInputStream fis = new FileInputStream(sourceFile);  //  J# input
							//stream to fill zip file
                /*
                    Add the entry to the zip file (The Replace will remove the full path
                    Ex.: file C:\FolderToZip\Files\Tmp\myFile.xml,
		  will be written as Files\Tmp\myFile.xml on the zip file
                    If this code was not written, it would generate the
		  whole tree since the beginning of the FolderToZip
                    This way the zip file begins directly at the contents
		  of C:\FolderToZip
                */

                ZipEntry ze = new ZipEntry(sourceFile.Replace(theDirectory + @"\", ""));
                zos.putNextEntry(ze);

                sbyte[] buffer = new sbyte[1024];
                int len;

                while ((len = fis.read(buffer)) >= 0)
                {
                    zos.write(buffer, 0, len);  //  Write buffer to Zip File
                }

                fis.close();    //  Close input Stream
            }

            //  Close outputs
            zos.closeEntry();
            zos.close();
            fos.close();

            sb.Append(String.Format("Folder {0} Zipped successfully to File {1}.<br/>",
						theDirectory, ZipFileName));

        }
        catch (Exception eX)
        {
            sb.Append(String.Format("Error zipping folder {0}. Details: {1}.
		Stack Trace: {2}.<br/>", theDirectory, eX.Message, eX.StackTrace));
        }

        lbReport.Text = sb.ToString();  //  Show result/report
    }

The physical folder to zip:

folder_to_zip.PNG

The result of the Web Application after pressing the button:

result.PNG

And the zipped files on the zip folder:

zipped_folders.PNG

Points of Interest

The most interesting point about this solution is that you can use both C# and J# libraries on the same code, compiling them together in order to complete a solution. C# for itself, with its standard libraries, does not provide zip methods. J# does, however, you are programming in C#. So, why not mix them together in the same solution?!?

Another interesting point is the fact that there are several solutions on the web, all of them being libraries that you can download, but you must pay for their license. This one uses .NET libraries exclusively, no third party solutions involved. 

History

After receiving some comments, a new version was generated, resizing the images, adding comments to the code and explaining this solution.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Portugal Portugal
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
joker220610-Dec-12 19:34
joker220610-Dec-12 19:34 
GeneralMy vote of 5 Pin
Deepak_Sharma_25-Oct-12 4:22
Deepak_Sharma_25-Oct-12 4:22 
QuestionThanks! Pin
sandeep56831-May-12 21:23
sandeep56831-May-12 21:23 
QuestionProblem on Deploying on Server Pin
freesmile21-Feb-12 9:36
freesmile21-Feb-12 9:36 
AnswerRe: Problem on Deploying on Server Pin
FormatException7-Mar-13 3:47
FormatException7-Mar-13 3:47 
GeneralRe: Problem on Deploying on Server Pin
FormatException7-Mar-13 3:49
FormatException7-Mar-13 3:49 
GeneralMy vote of 5 Pin
DineshMaind12-Feb-12 22:38
DineshMaind12-Feb-12 22:38 
QuestionQuite nice ! Pin
tjafaas29-Jan-12 23:14
tjafaas29-Jan-12 23:14 
GeneralMy vote of 4 Pin
tjafaas29-Jan-12 23:12
tjafaas29-Jan-12 23:12 
GeneralMy vote of 4 Pin
MoePOo12-Dec-10 19:32
MoePOo12-Dec-10 19:32 
NewsVisual J# Redistributable Package Pin
miladamirzadeh2-Dec-10 3:35
miladamirzadeh2-Dec-10 3:35 
GeneralRe: Visual J# Redistributable Package Pin
Cheeso26-Jul-11 14:57
Cheeso26-Jul-11 14:57 
AnswerRe: Visual J# Redistributable Package Pin
derekcoder27-Jul-11 15:10
derekcoder27-Jul-11 15:10 
Generalit still build the whole tree Pin
Jaci Ho13-Apr-10 22:45
Jaci Ho13-Apr-10 22:45 
GeneralRe: it still build the whole tree Pin
Cheeso26-Jul-11 14:59
Cheeso26-Jul-11 14:59 
GeneralWork great but you'll need J# redistribution package x64 or x86 Pin
Lau, Janson24-Feb-10 12:49
Lau, Janson24-Feb-10 12:49 
GeneralDon't use J# Pin
Cheeso11-Dec-09 21:04
Cheeso11-Dec-09 21:04 
GeneralHi Pin
drweb8620-Jul-09 2:27
drweb8620-Jul-09 2:27 
NewsGreat Library: www.codeplex.com/DotNetZip Pin
rzubi6-Nov-09 0:47
rzubi6-Nov-09 0:47 
GeneralAnother option Pin
seesharper8-Jul-09 0:16
seesharper8-Jul-09 0:16 
GeneralRe: Another option Pin
Bit-Smacker14-Jul-09 8:51
Bit-Smacker14-Jul-09 8:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.