Wednesday, March 4, 2009

Zip/Unzip using C#

I have spent few hours over internet to find out a way to create zip file using .net 2.0, C#. My intention was to avoid any third party library or application. I started with System.IO.Compression, but I did not find any resource about creating a zip from a directory with files and subdirectory as well. I got few .net library and I felt few of those are quite familier and using wiedly. But as I have some restriction i can not use those. Finally I got a solutoin to create and extract zip file using Shell32.dll. Here is two functions I wrote.

private static void ZipFile(string sourceFolder, string destinationFile)
byte[] emptyzip = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

FileStream fs = File.Create(destinationFile);
fs.Write(emptyzip, 0, emptyzip.Length);
fs = null;

//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(sourceFolder);
Shell32.Folder DestFlder = sc.NameSpace(destinationFile);
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);

private static string UnzipFile(string inputFileName, string destinationPath)
if (!Directory.Exists(destinationPath))

Shell shell = new ShellClass();
Folder sourceFolder = shell.NameSpace(inputFileName);
Folder destinationFolder = shell.NameSpace(destinationPath);
string outputFileName = sourceFolder.Items().Item(0).Name;
destinationFolder.CopyHere(sourceFolder.Items(), "");
return outputFileName;

Here is the code to call those function.

ZipFile(@"D:\SourceFolder", @"D:\");

UnzipFile(@"D:\", @"D:\ExtractFolder");

Hope this may help you. Thanks.


Alex said...

In this difficult situation I advise to use one nice tool-zip file larger than 2gb,which helped my familiar and me not once,program has many capacibilities and also software is free as far as I can see,it can save a lot of free space on hard drives and removable media,also split files, it is used, when forwarding large files by email,can work with all Windows family, from Windows 98 to Windows Vista,program for extracting zip files 2gb Microsoft,allows choosing only those files, that can be successfully repaired,save extracted documents to your hard drive and finish the process,can extract your documents from corrupted Zip files.

Alex said...

There are a lot of zip files on my PC. And one day something must have happened with my PC and all data were lost. I recovered most of lost data,but my xls files,where was my job files I couldn't. Today I by sheer chance observed a next tool - program to fix file compressed with winzip. I used it and was discouraged,by reason of it solved my issue for seconds and I didn't spend the money as far as I kept in mind. I hazard the remark that it helped my friend in like condition.

Anonymous said...

it works nicely, Thanks

Pavithra said...

Thanks a lot