C # zip compression and decompression help class package with source code download

Source: Internet
Author: User

C # is compressed and decompressed, which is encapsulated by a third-party class library. ICSharpCode. SharpZipLib. dll class library, which can be downloaded from your official website. Compression is mainly performed using stream compression.

Compress files and folders. File compression is simple. You can read the files to be compressed into the memory in the stream mode and put them in the compressed stream. You can. Folder is a little troublesome. Because you need to extract the folder to be compressed and keep the hierarchical structure of the folder file. So my implementation method is to recursively traverse the files in the folder. Computation the relative position to the compressed stream.

The Code is as follows:

Copy codeThe Code is as follows: // <summary>
/// Compressed file or folder
/// </Summary>
/// <Param name = "_ depositPath"> the compressed file storage path, for example, C: \ windows \ abc.zip </param>
/// <Returns> </returns>
Public bool CompressionZip (string _ depositPath)
{
Bool result = true;
FileStream fs = null;
Try
{
ZipOutputStream ComStream = new ZipOutputStream (File. Create (_ depositPath ));
ComStream. SetLevel (9); // compression level
Foreach (string path in AbsolutePaths)
{
// If it is a directory
If (Directory. Exists (path ))
{
ZipFloder (path, ComStream, path );
}
Else if (File. Exists (path) // if it is a File
{
Fs = File. OpenRead (path );
Byte [] bts = new byte [fs. Length];
Fs. Read (bts, 0, bts. Length );
ZipEntry ze = new ZipEntry (new FileInfo (path). Name );
ComStream. PutNextEntry (ze); // provides a container for the compressed file stream
ComStream. Write (bts, 0, bts. Length); // Write bytes
}
}
ComStream. Finish (); // end Compression
ComStream. Close ();
}
Catch (Exception ex)
{
If (fs! = Null)
{
Fs. Close ();
}
ErrorMsg = ex. Message;
Result = false;
}
Return result;
}
// Compress the folder
Private void ZipFloder (string _ OfloderPath, ZipOutputStream zos, string _ floderPath)
{
Foreach (FileSystemInfo item in new DirectoryInfo (_ floderPath). GetFileSystemInfos ())
{
If (Directory. Exists (item. FullName ))
{
ZipFloder (_ OfloderPath, zos, item. FullName );
}
Else if (File. Exists (item. FullName) // if it is a File
{
DirectoryInfo ODir = new DirectoryInfo (_ OfloderPath );
String fullName2 = new FileInfo (item. FullName). FullName;
String path = ODir. Name + fullName2.Substring (ODir. FullName. Length, fullName2.Length-ODir. FullName. Length); // obtain the relative directory
FileStream fs = File. OpenRead (fullName2 );
Byte [] bts = new byte [fs. Length];
Fs. Read (bts, 0, bts. Length );
ZipEntry ze = new ZipEntry (path );
Zos. PutNextEntry (ze); // provides a container for the compressed file stream
Zos. Write (bts, 0, bts. Length); // Write bytes
}
}
}

It is much easier to decompress the package. Files are extracted, folders are traversed, and files are extracted. The decompressed file contains the hierarchical relationship between it and the folder.

Copy codeThe Code is as follows: // <summary>
/// Extract
/// </Summary>
/// <Param name = "_ depositPath"> compressed file path </param>
/// <Param name = "_ floderPath"> decompressed path </param>
/// <Returns> </returns>
Public bool DeCompressionZip (string _ depositPath, string _ floderPath)
{
Bool result = true;
FileStream fs = null;
Try
{
ZipInputStream InpStream = new ZipInputStream (File. OpenRead (_ depositPath ));
ZipEntry ze = InpStream. GetNextEntry (); // obtain each file in the compressed file
Directory. CreateDirectory (_ floderPath); // create an extract folder
While (ze! = Null) // If ze is decompressed, It is null.
{
If (ze. IsFile) // compress zipINputStream to store all files. The file name with folders is Folder \ file name
{
String [] strs = ze. Name. Split ('\'); // if the file Name contains '\', a folder exists.
If (strs. Length> 1)
{
// Two layers of loops are used to create folders on one layer
For (int I = 0; I <strs. Length-1; I ++)
{
String floderPath = _ floderPath;
For (int j = 0; j <I; j ++)
{
FloderPath = floderPath + "\" + strs [j];
}
FloderPath = floderPath + "\" + strs [I];
Directory. CreateDirectory (floderPath );
}
}
Fs = new FileStream (_ floderPath + "\" + ze. Name, FileMode. OpenOrCreate, FileAccess. Write); // create a file
// Read the file to the file stream cyclically
While (true)
{
Byte [] bts = new byte [1024];
Int I = InpStream. Read (bts, 0, bts. Length );
If (I> 0)
{
Fs. Write (bts, 0, I );
}
Else
{
Fs. Flush ();
Fs. Close ();
Break;
}
}
}
Ze = InpStream. GetNextEntry ();
}
}
Catch (Exception ex)
{
If (fs! = Null)
{
Fs. Close ();
}
ErrorMsg = ex. Message;
Result = false;
}
Return result;
}

Finally, let's make a summary. C # as an advanced language, its powerful class libraries and third-party class libraries. You can do many things. However, the performance of third-party class libraries is not very high. I compress hundreds of MB of data. The cpu instantly reaches more than 50%. This is far worse than 360 compression and zip compression. Therefore, this class applies to small compression.

Complete example

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.