Compress and decompress files using SharpZipLib in C #

Source: Internet
Author: User
Tags crc32

I needed to compress and decompress the files when I was doing the project, so I started from http://www.icsharpcode.net (http://www.icsharpcode.net/OpenSource/SharpZipLib/ Download.aspx downloaded the source of compression and decompression, but after downloading, faced with so many code, do not know how to start. Had to withstand the heart, slowly study, finally found the way. Two classes of file compression and decompression were rewritten for their own needs, Zipclass and Unzipclass. In which encountered a lot of difficulties, decided to write to compress and decompress the program, the source must be affixed to share, so that the first contact compression and decompression of friends can take a few detours. The following explains how to compress and decompress files in C # with http://www.icsharpcode.net downloaded sharpziplib.

First, you need to refer to SharpZipLib.dll in your project. Then modify the classes in which the compression and decompression are related. Realize the source code as follows:


/**/<summary>
Compress files
</summary>

Using System;
Using System.IO;

Using ICSharpCode.SharpZipLib.Checksums;
Using ICSharpCode.SharpZipLib.Zip;
Using ICSharpCode.SharpZipLib.GZip;

Namespace Compression
{
public class Zipclass
{

public void ZipFile (string filetozip, string zipedfile, int compressionlevel, int BlockSize)
{
If the file is not found, the error
if (! System.IO.File.Exists (Filetozip))
{
throw new System.IO.FileNotFoundException ("The specified file" + Filetozip + "could not be found. Zipping Aborderd ");
}

System.IO.FileStream streamtozip = new System.IO.FileStream (Filetozip,system.io.filemode.open, System.IO.FileAccess.Read);
System.IO.FileStream ZipFile = System.IO.File.Create (zipedfile);
Zipoutputstream ZipStream = new Zipoutputstream (ZipFile);
ZipEntry zipentry = new ZipEntry ("Zippedfile");
Zipstream.putnextentry (ZipEntry);
Zipstream.setlevel (CompressionLevel);
byte[] buffer = new Byte[blocksize];
System.Int32 size =streamtozip.read (buffer,0,buffer. Length);
Zipstream.write (buffer,0,size);
Try
{
while (Size < streamtozip.length)
{
int Sizeread =streamtozip.read (buffer,0,buffer. Length);
Zipstream.write (Buffer,0,sizeread);
Size + = Sizeread;
}
}
catch (System.Exception ex)
{
Throw ex;
}
Zipstream.finish ();
Zipstream.close ();
Streamtozip.close ();
}

public void Zipfilemain (string[] args)
{
string[] filenames = Directory.GetFiles (args[0]);

Crc32 CRC = New Crc32 ();
Zipoutputstream s = new Zipoutputstream (File.create (args[1]));

S.setlevel (6); 0-store-9-means Best compression

foreach (string file in filenames)
{
Open compressed file
FileStream fs = File.openread (File);

byte[] buffer = new BYTE[FS. Length];
Fs. Read (buffer, 0, buffer. Length);
FileInfo info = new FileInfo (file);
ZipEntry entry = new ZipEntry (info.   Name); The path shown after compression is the currently compressed directory

ZipEntry entry = new ZipEntry (file); Show full path after compression
Entry. DateTime = DateTime.Now;

Set Size and the CRC, because the information
About the size and CRC should is stored in the header
If it isn't set it is automatically written in the footer.
(in this case size = = CRC = =-1 in the header)
Some zip programs has problems with zip files, that don ' t store
The size and CRC in the header.
Entry. Size = fs. Length;
Fs. Close ();

Crc. Reset ();
Crc. Update (buffer);

Entry. CRC = CRC. Value;

S.putnextentry (entry);

S.write (buffer, 0, buffer.) Length);

}

S.finish ();
S.close ();
}
}
}



Now take a look at the source of the extracted file class


/**/<summary>
Unzip the file
</summary>

Using System;
Using System.Text;
Using System.Collections;
Using System.IO;
Using System.Diagnostics;
Using System.Runtime.Serialization.Formatters.Binary;
Using System.Data;

Using ICSharpCode.SharpZipLib.BZip2;
Using ICSharpCode.SharpZipLib.Zip;
Using ICSharpCode.SharpZipLib.Zip.Compression;
Using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
Using ICSharpCode.SharpZipLib.GZip;

Namespace decompression
{
public class Unzipclass
{
public void UnZip (string[] args)
{
Zipinputstream s = new Zipinputstream (File.openread (args[0]));

ZipEntry Theentry;
while ((Theentry = S.getnextentry ()) = null)
{

String directoryname = Path.getdirectoryname (args[1]);
String fileName = Path.getfilename (theentry.name);

Create an Extract directory
Directory.CreateDirectory (directoryname);

if (fileName! = String.Empty)
{
Unzip the file to the specified directory
FileStream streamWriter = file.create (args[1]+theentry.name);

int size = 2048;
byte[] data = new byte[2048];
while (true)
{
Size = s.read (data, 0, data. Length);
if (Size > 0)
{
StreamWriter.Write (data, 0, size);
}
Else
{
Break
}
}

StreamWriter.Close ();
}
}
S.close ();
}
}

After a class with compression and decompression, it is called in the form. How? is novice, not called? Ok, and then look down at how to invoke it in the form.

First put two command buttons in the form (Don't tell me you won't put it), then write the following source code


/**/<summary>
Call source
</summary>

private void Button2_click_1 (object sender, System.EventArgs e)
{&NBSP;
   string []FileProperties=new string[2];  
   fileproperties[0]= "c:/unzipped/";//file directory to be compressed  
    Fileproperties[1]= "C:/zip/a.zip";   //compressed target file  
   ZipClass Zc=new  Zipclass ();  
   zc.zipfilemain (fileproperties);  
  } 
 
     private void button2_click (object sender,  system.eventargs e)  
  {&NBSP;
    string []fileproperties=new string[2]; 
   fileproperties[0]= "C:/zip/test.zip ";//file to be unzipped  
   fileproperties[1]=" c:/unzipped/";//target directory   after decompression;
    unzipclass unzc=new unzipclass ();  
   unzc.unzip (FileProperties); 
  } 

Compressing and decompressing files with SharpZipLib in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.