Create, Analyze and Manipulate Zip Files in C# Dot Net


Manipulating zip files in .NET with the generic ZipPackage Class is bit complex since you have to add the MIME types for the files you are going to use in the Zip files. I came across this library called DotNetZip library, when I was trying to create a folder analyzing tool for my Search application. Data analysis is very important in enterprise search, but all the folder analyzing utilities that are available, considers zip file as a single file and skip to look into the files inside it. Hence I started developing a utility that would list the files inside directories, sub directories and files inside zip files as well. I used DotNetZip library for the zip files part of the program and found it to be very useful, fast and simple to code.

DotNetZip library is a very simple, easy to use yet more efficient and 100 % dotnet managed code. It can be used in any .NET application such as Console, Winforms, WPF, ASP.NET, Sharepoint, Web Services apps and so on. It is freely available and also capable of handling ZIP64 files. It also supports other features of Zip files such as zip passwords, AES encryption, self extracting zip, spanned archives, Unicode.etc.

Here are the steps to create, analyze and manipulate zip files using DotNetZip library in a simple windows forms application.

1. First of all download DotNetZip library development kit from here. Navigate to \DotNetZipLib-DevKit-v1.9\zip-v1.9\Release folder where you can find the Ionic.Zip dll file.

2. Create Windows forms application, go to Solutions explorer > Right Click References > Click Add Reference > Move to Browse Tab > Navigate to \DotNetZipLib-DevKit-v1.9\zip-v1.9\Release folder and add Ionic.Zip dll to the project.

Creating Zip File

3. Create a form with a button and two text boxes, one to get the input directory that contains the files to be zipped and the other to get the output zip file name with path.



3. Double click the "Zip it!" button and add the following code in button click event.

 private void button3_Click(object sender, EventArgs e)
   {
     using (ZipFile zip = new ZipFile())
      {
        string inputdirectory = textBox1.Text;
        string outputdirectory = textBox2.Text;
        inputdirectory = inputdirectory.Replace("\\", "\\\\");
        outputdirectory = outputdirectory.Replace("\\", "\\\\");
        zip.AddDirectory(inputdirectory, "ZipTest");
        zip.Comment = "This zip file is created using DotNetZip library";
        zip.Save(outputdirectory);
      }
   }

The above code will zip up all the files in an entire directory including the sub directories in it and will have a comment on the zip archive it is creating. You can also add individual files to the zip file and specify which directory to use inside the zip file you are creating with the following code. 

 string[] filenames=  {"C:\Users\Desktop\test.txt",
                       "D:\Academics\extractdata.pdf","D:\reports.csv"};
 using (ZipFile zip = new ZipFile())
      {
        zip.AddFiles(filenames,"DirectoryInsideZip");
        zip.Save("Test.zip");
      }


You can find more example codes on creating zip files with password protection, AES encryption, different compression levels.etc here.

Extracting Zip files

4. Create a form with a button and two text boxes, one to get the path of the zip file to be extracted and the other to get the output directory to which the zip file would be extracted to.


5. Double click the "Unzip it!" button and paste the following code to extract the zip file in the specified output directory.

private void button3_Click(object sender, EventArgs e)
  {
     using (ZipFile zip = new ZipFile())
      {
        string zipToExtract = textBox1.Text;
        string unzipDirectory = textBox2.Text;
        zipToExtract=zipToExtract.Replace("\\","\\\\");
        unzipDirectory=unzipDirectory.Replace("\\","\\\\");
        using (ZipFile zip1 = ZipFile.Read(zipToExtract))
          {
           foreach(ZipEntry en in zip1)
            {
              en.Extract(unzipDirectory,    
                      ExtractExistingFileAction.OverwriteSilently);
            }
          }
      }
  }

The above code extracts zip file to the specified directory. If there are any files present in the directory with the same name as that of the files inside zip files, the 'OverWriteSilently' option will silently overwrite the files. There are also other options such as,'DoNotOverwrite', 'InvokeExtractProgressEvent'  and 'Throw'. You can decide on which one to use according to your requirement.

Analyze Files inside Zip files

6. Create a form with a button, a text box to get the zip file name with path to analyze and a data grid view to display the analysis results.


7. Double click the "Analyze Zip File" button and paste the below code.

 private void button3_Click(object sender, EventArgs e)
        {
            string filePath=textBox1.Text;
            filePath = filePath.Replace("\\", "\\\\");
            DataTable ziptable = new DataTable();
            ziptable.Columns.Add("File Name");
            ziptable.Columns.Add("File Size");
        
            using (ZipFile zip = ZipFile.Read(filePath))
            {
                foreach (ZipEntry en in zip)
                {
                    ziptable.Rows.Add(en.FileName, en.CompressedSize);
                }
            }
            dataGridView1.DataSource = ziptable;
        }

The above code displays the file name and compressed size of each entry inside zip files. You can also get the uncompressed size, last modified date, creation date and much more about the files inside zip files. Please note that it does not reveal the details of files inside nested zip files( zip files inside zip files).

You can also update, add and delete files inside already existing zip files with DotNetZip library.


Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.




Subscribe to GET LATEST ARTICLES!


advertise here

Related

Dot Net 4785213147981901647

Post a Comment

  1. Thanks for this information dear. I am eager to read some more useful information regarding ASP.NET Development Services.

    ReplyDelete
  2. While dealing with .NET I came to work with DotNetZip, I think this is so far the best library and tool set to adjust zip files. As it is free, reliable and fast no developer is going to ignore it.

    ReplyDelete
  3. Hi
    While trying this code.. I got an error on the line "zip.AddDirectory(inputdirectory,"Zip Test");"
    The error says..."the directory name is invalid"...
    Kindly guide me through

    ReplyDelete
    Replies
    1. Hi,

      You will get this error when you try to create a zip file using a folder that does not exist.Check whether the value of inputdirectory is valid.

      Hope this helps!

      Hope this helps!

      Delete
  4. Is there any way to extract a file without including the directory structure?
    Thanks

    ReplyDelete
  5. im getting an error while making a zip the second time having the same files i.e i cannot create another zip file containing the same files as it says "An item with the same key has already been added."
    the error arises at zip.Addfile(what so ever file);
    searching this i got to know i have to change the dictionary container.. Now i Need help on that.

    ReplyDelete

emo-but-icon

Currency Converter

Built using AngularJS and ASP.NET Web API

SUBSCRIBE


item