Click here to Skip to main content
Email Password   helpLost your password?

Introduction

There are a lot of libraries to work with zip files. I found a very easy way to work with zip files from a C# program. The Microsoft .Net Framework 1.1 comes with new language: J#. Let's look at it a little. For sure, Java is a parent of it; if so, java.util.zip is somewhere here! I spent a few minutes and found it in vjslib.dll. Let's do the work. Start a new C# project and select Windows Application. Our goal is something like that:

All we need to do is: add reference to our project:

Now, we can use it:

// Output stream 

java.io.FileOutputStream fos = new java.io.FileOutputStream(zipFileName); 

// Tie to zip stream 

java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos); 

// Stream with source file 

java.io.FileInputStream fis = new java.io.FileInputStream(sourceFile); 

// It's our entry in zip 

java.util.zip.ZipEntry ze = new java.util.zip.ZipEntry(sourceFile); 

zos.putNextEntry(ze); 
sbyte[] buffer = new sbyte[1024]; 
int len; 

// Read and write until done 

while((len = fis.read(buffer)) >= 0) 
{ 
    zos.write(buffer, 0, len); 
}
 
// Close everything 

zos.closeEntry(); 
fis.close(); 
zos.close(); 
fos.close(); 

Conclusion

That's all! Demo application is included.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralWhat about cyrillics?
chien-andalou
6:32 16 Jul '09  
Great article, congratulations!

But do you have any idea how to prevent the corruption of file names that contain cyrillics?
E.g. I zip the file named "привет, мир.txt", but when I extract it from the archive I receive "яЁштхЄ, ьшЁ.txt".
GeneralHanging onto corrupt file
terry summers
11:16 22 Mar '09  
Hi and thank you very much for the informative article.
I have one problem with this which I cannot figure out.
I'm using this to unzip some files. Pretty basic really.
In testing I gave it a corrupt file (to be able to trap the error and rename the zip as a bad zip file)

It gets as far as ZipFile zipfile = new ZipFile(ZipFileName);
The error gets trapped, however the class is still hanging onto the file so I can't rename it (or in fact do anything with it) until I shut down the program.

Would you know what would be holding onto the file?

Thanks in advance,
Terry
Questionunzipped progress status
byteway
22:38 2 Oct '07  
Hi,

Super article! Read it and now using it. How can I show unzip status in a progress bar? I can get the size of the file being unzipped together with the size of buf (what's actually unzipped to the outputstream) I thought I could show some kind of status. But the problem is that I get the size of the file within the zipfile, this means that: when I set the maximum value to the file size and the status value to the buffer size, I get an error because the unzipped buf size is bigger... Please tell me how to deal with this...
QuestionUnzip file stored in database
mikebiro
13:11 1 Oct '07  
All the examples I see, including yours, assume that the zipped file is in the file system. What about a zip file stored as a BLOB in a database? Is there a way to get the zipped file from the database and unzip it without having to write it somewhere first?

I have zip files in a SQL Server table and I want to retrieve them from the database, unzip them, and then process them further, all before having to write them somewhere.
GeneralCan I zip without folder structure?
jupinno_ys
22:57 15 Aug '07  
Can I zip without folder structure?

Example:

if I want to zip: D:\myFolder\images\*.*

the zipped output always contains folder myFolder\images\

Can I have the files when it's unzip without above folder structure, and directly list the images on root unzipped folder?

Hope this is clear, thks
AnswerRe: Can I zip without folder structure?
PranaySharma84
4:55 27 Aug '07  
Actually this code is really flexible and if you see the line
java.util.zip.ZipEntry ze = new java.util.zip.ZipEntry("")
If you dont want folder structure just dont provide it in ZipEntry

Here is what i did to the code and archived this:


public class zipit
{
public zipit(String path,String filename)
{
if(File.Exists(path+filename+".zip"))
{
File.Delete(path+filename+".zip");
}
java.io.FileOutputStream fos = new java.io.FileOutputStream(path+filename+".zip");
Console.Write("Doing");
// Tie to zip stream
java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos);

// Stream with source file
java.io.FileInputStream fis = new java.io.FileInputStream(path+filename+".mde");

// It's our entry in zip
java.util.zip.ZipEntry ze = new java.util.zip.ZipEntry(filename + ".mde");

zos.putNextEntry(ze);
sbyte[] buffer = new sbyte[1024];
int len;

// Read and write until done
while ((len = fis.read(buffer)) >= 0)
{
zos.write(buffer, 0, len);
}

// Close everything
zos.closeEntry();
fis.close();
zos.close();
fos.close();

}
}




Pranay Sharma
Web Analyst
Future Strategies Inc.
http://www.pranaysharma.com/

GeneralProblem in unzip
hamidreza Talebi
2:18 7 Aug '07  
I wanna unzip some zip files , but I got this error:
Could not find a part of the path 'D:\Inetpub\wwwroot\fanavadc\cache\blue\content.css'

amazing thing for me is I can unzip some file.can u help me?

HRT

QuestionSize of Zipped File
kyreddy
5:00 26 Jun '07  
Hi,this is a good stuff .Bt zipped files size is same as the total size of the zipped files.Can you suggest me wat should i do to get some compressed in size for zip file.
Generalzip files with password
3:21 24 Feb '07  
Hi,

I just check the project from Valeri EasyZipUnzip_Demo, that what I'm looking for.
Unfortunetly I wish to zip and unzip files with password, is it possible?

Thanks in andvance.


Naim
GeneralRe: zip files with password
Valeri
20:47 18 Apr '07  
Hi,

There is no support for password-protected files. You could create your own encryption mechanism using the classes in the System.Security.Cryptography namespace. If you do this, be aware that the resulting file will not be compatible with standard Zip utilities such as WinZip.

With best regars,
Valeri
GeneralRe: zip files with password
amit_2006_it@yahoo.com
10:05 6 Jun '07  
Can we unzip the files using ur code.
by writing revers?
GeneralRe: zip files with password
Valeri
8:13 7 Jun '07  
Yes. Did you look my code?
GeneralHow to unzip password protected zip files?
sakthivenkatesh
14:04 22 Feb '07  
Hi,

Thanks for the article. By the way how can we unzip password protected zip files - would be of great help if you could let me know.

Thanks and Regards,
Venkatesh.

GeneralRe: How to unzip password protected zip files?
Valeri
20:53 18 Apr '07  
Hi,

There is no support for password-protected files.:(

With best regards,
Valeri
GeneralGood job
joachimF
0:52 7 Dec '06  
Short and to the point. Thanks!

--
Ubi Signo?

GeneralHow can we unzip password-protected files.
Anjum Rizwi
20:56 26 Nov '06  
How can we unzip password-protected files.
GeneralIs it possible to read in the middle of the zip file?
shultas
16:52 30 Aug '06  
We have thousands and thousands of zip files on our server. I have written a program that opens up these zip files and extracts certain files from them (i.e, *.doc files). I have been doing this over VPN, and it is much slower than going into the office. Most of the time I only need one .DOC file that is in a 5 or 10MB zip, and it happens to be the last file stored in most of the zips. What is happening is that the program is reading the zip file until it finds a file it wants and then extracts only that file. The problem is since these files are stored at the end of the .ZIP, it takes many minutes for it to iterate through all of the files that are in the ZIP (even though I don't want to do anything with them, or try to read them, etc...) and it just takes a while.

I am wondering if ZIP stores the file contents in a header, and if it does, if it is possible to just read that header, figure out what files you need and what byte offset it is at and then "skip" right to that file without reading the entire zip file? This would make my helper application a million times faster. I've looked around for other solutions but I can't seem to see any that can do it, it appears as if this Java class needs to read the contents of the entire file to get you what you want.

Thanks!
AnswerRe: Is it possible to read in the middle of the zip file?
Valeri
21:21 30 Aug '06  
ZIP stores the file information at the end of .zip. It reads this information first to know where to get the file.
GeneralRe: Is it possible to read in the middle of the zip file?
shultas
12:19 31 Aug '06  
ahh, that explains it!
so does the library actually read every byte until it finds the header, or does it do skipping around?

just curious as to if there is some way around reading the entire file to get a file that is at the beginning (probably not, but the many hours and hours saved if there is is worth the post!)

thanks for the reply .. oh and by the way, thanks for the POST. I looked and looked and never could have imagined it being so easy!

S
GeneralZip Folder qithin a zip folder
M Ali Raza
22:02 5 Apr '06  
I studied your article "Zip and Unzip from a C# program using J# runtime" and it is quite helpful.
But i am getting problem that if a zip folder containes andother zip folder or a folder named *.rar then
"java.util.zip.ZipEntry ze = new java.util.zip.ZipEntry(sourceFile);"
za dont get it correctly and throws and exception.
If you can help me pleez to get out of it.
Regards.
M.Ali.Raza
GeneralProblem In Latin FileNames
dealarconjose
2:03 15 Mar '06  
java.util.zip.ZipEntry does not support fileNames like "deAlarcón.doc"
What can i do? thank's
GeneralAlternative (with code)
Elmue
1:41 21 Nov '05  
Hello

As vjslib is buggy (don't use it) try this one:
http://www.icsharpcode.net/OpenSource/SharpZipLib/
There are 3 advantegaes over vjslib:
1.) It works without bugs.
2.) It also supports GZip, Tar and BZip2 .
3.) The DLL you need is only 140 kB instead of 3,7 MB.

The SharpZipLib has a good detailed documentation but it lacks examples.
So I post my code here which I use to zip a whole folder into a ZIP file.

Elmü

using ICSharpCode.SharpZipLib.Zip;

/// /// Packs a folder and all files in all its subfolders into a ZIP file preserving the relative paths
/// Requires ICSharpCode.SharpZipLib library
/// http://www.icsharpcode.net/OpenSource/SharpZipLib
///
static public void PackFolderIntoZipFile(string s_Folder, string s_ZipFile)
{
ZipOutputStream i_zStream = new ZipOutputStream(File.Create(s_ZipFile));
i_zStream.SetLevel(5); // Compression level (0-9)
int s32_BaseFolderLen = s_Folder.Length;
if (s_Folder.Substring(s_Folder.Length-1) != "\\") s32_BaseFolderLen ++;

ArrayList i_FileList = new ArrayList();
EnumFiles(ref i_FileList, s_Folder, "*.*", true);

Byte[] u8_Buf = new Byte[0x100000]; // 1 Megabyte buffer
foreach (string s_File in i_FileList)
{
FileStream i_fStream = null;
// Catch errors of files which are locked (cannot be opened)
try { i_fStream = File.OpenRead(s_File); }
catch { continue; }

// Cut the base folder ("E:\ZipFolder\Subfolder\File.txt" -> "Subfolder/File.txt")
// The zip archive requires "/" as separator
string s_ZipPath = s_File.Substring(s32_BaseFolderLen).Replace("\\", "/");

ZipEntry i_ZipEntr = new ZipEntry(s_ZipPath);
FileInfo i_Info = new FileInfo(s_File);
i_ZipEntr.DateTime = i_Info.LastWriteTime;
i_zStream.PutNextEntry(i_ZipEntr);

while (true)
{
int s32_Len = i_fStream.Read(u8_Buf, 0, u8_Buf.Length);
if (s32_Len <= 0)
break;

i_zStream.Write(u8_Buf, 0, s32_Len);
}

i_fStream.Close();
}

i_zStream.Finish();
i_zStream.Close();
}

/// /// This recursive function searches all files in the given folder and its subfolders
/// s_Filter = "*.Extension"
/// s_Path = Start path
///
static public void EnumFiles(ref ArrayList i_FileList, string s_Path, string s_Filter, bool b_Subfolders)
{
if (s_Path == null || s_Path == "")
return;

string[] s_Files = Directory.GetFiles(s_Path, s_Filter.Trim());
foreach (string s_File in s_Files)
{
i_FileList.Add(s_File);
}

if (b_Subfolders)
{
string[] s_Dirs = Directory.GetDirectories(s_Path);
foreach (string s_Dir in s_Dirs)
{
EnumFiles(ref i_FileList, s_Dir, s_Filter, true);
}
}
}

GeneralWhat about multiple folders?
dragomir
1:54 22 Dec '05  
Hello,

Thanks for this rather useful piece of code. What about zipping multiple folders with their subfolders in 1 archive?

-Drago
GeneralRe: What about multiple folders?
Elmue
2:53 31 Dec '05  
Hello

This is quite a useless question.
If you would have studied and understood my code you should be able to answer this question on your own!

Simply call

EnumFiles(ref i_FileList, s_Folder, "*.*", true);

once for each folder you want to add !
Thats all !

Elmü
GeneralRe: What about multiple folders?
wyattda
18:36 17 Jan '06  
Nice work.. Though you could use a little manners training Smile


Last Updated 26 Apr 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010