The compressed namespace and method added in. NET 4.5. You can discard the class library ICSharpCode. SharpZipLib. dll. Performance comparable. But it can greatly simplify your code. If you start to use. NET FrameWork4.5 for compression, try the built-in compression method.
Traditionally, the code written by ICSharpCode. SharpZipLib. dll is used.
Copy codeThe Code is as follows:
Static void Main (string [] args)
{
Stopwatch watch = new Stopwatch ();
Watch. Start ();
String path = @ "E :\";
Compress (Directory. GetFiles (path), @ "F: \ 4.0.zip ");
Watch. Stop ();
Console. WriteLine ("consumed time: {0}", watch. ElapsedMilliseconds );
FileInfo f = new FileInfo (@ "F: \ 4.0.zip ");
Console. WriteLine ("file size {0}", f. Length );
}
Static void Compress (string [] filePaths, string zipFilePath)
{
Byte [] _ buffer = new byte [4096];
If (! Directory. Exists (zipFilePath ))
Directory. CreateDirectory (Path. GetDirectoryName (zipFilePath ));
Using (ZipOutputStream zip = new ZipOutputStream (File. Create (zipFilePath )))
{
Foreach (var item in filePaths)
{
If (! File. Exists (item ))
{
Console. WriteLine ("the file {0} not exist! ", Item );
}
Else
{
ZipEntry entry = new ZipEntry (Path. GetFileName (item ));
Entry. DateTime = DateTime. Now;
Zip. PutNextEntry (entry );
Using (FileStream fs = File. OpenRead (item ))
{
Int sourceBytes;
Do
{
SourceBytes = fs. Read (_ buffer, 0, _ buffer. Length );
Zip. Write (_ buffer, 0, sourceBytes );
} While (sourceBytes> 0 );
}
}
}
Zip. Finish ();
Zip. Close ();
}
}
Use the. NET FrameWork 4.5 self-contained compression.
Copy codeThe Code is as follows:
Static void Main (string [] args)
{
Stopwatch watch = new Stopwatch ();
Watch. Start ();
String path = @ "E :\";
Compress (path, @ "F: \ 4.5.zip ");
Watch. Stop ();
Console. WriteLine ("consumed time: {0}", watch. ElapsedMilliseconds );
FileInfo f = new FileInfo (@ "F: \ 4.5.zip ");
Console. WriteLine ("file size {0}", f. Length );
}
Static void Compress (string filePath, string zipFilePath)
{
ZipFile. CreateFromDirectory (filePath, zipFilePath, CompressionLevel. Fastest, false );
}
How is the code much simpler?