The following two methods are provided to compress and decompress files in C:
Use the open-source sharpziplib. The following code uses sharpziplib for simple encapsulation of the compression and decompression class:
/// <Summary>
/// Fileziplib compression, decompressed class
/// </Summary>
Public class fileziplib
{
Public fileziplib (){}
/// <Summary>
/// Create a compressed file
/// </Summary>
/// <Param name = "zipfilename"> compressed file name </param>
/// <Param name = "sourcedirectory"> directory of the file to be compressed </param>
Public static void packfiles (string zipfilename, string sourcedirectory)
{
Fastzip FZ = new fastzip ();
FZ. createemptydirectories = true;
FZ. createzip (zipfilename, sourcedirectory, true ,"");
FZ = NULL;
}
/// <Summary>
/// Decompress the file
/// </Summary>
/// <Param name = "zipfile"> files to be decompressed </param>
/// <Param name = "directory"> directory of the decompressed file </param>
Public static bool unpackfiles (string zipfile, string directory)
{
If (! Directory. exists (directory ))
Directory. createdirectory (directory );
Zipinputstream zis = new zipinputstream (file. openread (zipfile ));
Zipentry theentry = NULL;
While (theentry = Zis. getnextentry ())! = NULL)
{
String directoryname = path. getdirectoryname (theentry. Name );
String filename = path. getfilename (theentry. Name );
If (directoryname! = String. Empty)
Directory. createdirectory (directory + directoryname );
If (filename! = String. Empty)
{
Filestream streamwriter = file. Create (path. Combine (directory, theentry. Name ));
Int size = 2048;
Byte [] DATA = new byte [size];
While (true)
{
Size = Zis. Read (data, 0, Data. Length );
If (size> 0)
Streamwriter. Write (data, 0, size );
Else
Break;
}
Streamwriter. Close ();
}
}
Zis. Close ();
Return true;
}
}
Do not forget using icsharpcode. sharpziplib. Zip;
The above Code makes a small modification by referring to using sharpziplib to conveniently compress and decompress files.
Another method is to use the Microsoft J # class library. For details, refer to the msdn article:
Use the zip class in the J # class library to compress files and data through C #.
This article first in http://www.365keyi.com/article.asp? Id = 5