Use SharpZipLib in C # To Compress and decompress files.

Source: Internet
Author: User
Tags crc32

When working on a project, I need to compress and decompress the file. I was so patient that I finally found a way to study it. The two classes for File compression and decompression are rewritten for their own needs, namely ZipClass and UnZipClass. After encountering a lot of difficulties, I decided to write the program for compression and decompression, and I must paste the source code for sharing, so that the first contact with compression and decompression can take less detours. The following explains how to use http://www.icsharpcode.net/to download and decompress the sharpziplibline file in C.

First, you must reference SharpZipLib. dll in the project. Then modify the compression and decompression class. The source code is as follows:

/// <Summary>
/// Compressed file
/// </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, an error is returned.
If (! System. IO. File. Exists (FileToZip ))
{
Throw new System. IO. FileNotFoundException ("The specified file" + FileToZip + "cocould 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 = 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 only to 9-means best compression

Foreach (string file in filenames)
{
// Open the compressed file
FileStream fs = File. OpenRead (file );

Byte [] buffer = new byte [fs. Length];
Fs. Read (buffer, 0, buffer. Length );
ZipEntry entry = new ZipEntry (file );

Entry. DateTime = DateTime. Now;

// Set Size and the crc, because the information
// About the size and crc shocould be stored in the header
// If it is not set it is automatically written in the footer.
// (In this case size = crc =-1 in the header)
// Some ZIP programs have problems with zip files that dont 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 let's take a look at the source code of the decompressed File class.

/// <Summary>
/// Decompress 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 );

// Generate the extract directory
Directory. CreateDirectory (directoryName );

If (fileName! = String. Empty)
{
// Extract 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 ();
}
}
}

With the compression and decompression class, you need to call it in the form. Why? Is it a newbie and cannot be called? OK, and then let's see how to call it in the form.

First, place two command buttons in the form (don't tell me you won't put them ~), Then write the following source code

/// <Summary>
/// Call the source code
/// </Summary>

Private void button2_Click_1 (object sender, System. EventArgs e)
{
String [] FileProperties = new string [2];
FileProperties [0] = "C: \ unzipped \"; // the file to be compressed

Related Article

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.