ASP tutorial. NET C # zip file compression and decompression
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;
Using Icsharpcode.sharpziplib.zip;
Using System.Diagnostics;
Using Icsharpcode.sharpziplib.core;
Namespace TestConsole
{
Class Program
{
static void Main ()
{
Createzipfile (@ "D:", @ "D:a.zip");
Unzipfile (@ "D:a.zip");
Console.read ();
}
private static void Createzipfile (String filespath, String zipfilepath)
{
if (!directory.exists (Filespath))
{
Console.WriteLine ("Cannot find directory ' {0} '", Filespath);
Return
}
Try
{
string[] filenames = Directory.GetFiles (Filespath);
using (zipoutputstream s = new Zipoutputstream (File.create (Zipfilepath)))
{
S.setlevel (9); Compression level 0-9
S.password = "123"; Zip compressed file password
byte[] buffer = new byte[4096]; Buffer size
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry (path.getfilename (file));
Entry.datetime = DateTime.Now;
S.putnextentry (entry);
using (FileStream fs = file.openread (file))
{
int sourcebytes;
Todo
{
sourcebytes = fs.read (buffer, 0, buffer.length);
S.write (buffer, 0, sourcebytes);
while (sourcebytes > 0);
}
}
S.finish ();
S.close ();
}
}
catch (Exception ex)
{
Console.WriteLine ("exception during processing {0}", ex);
}
}
private static void Unzipfile (String zipfilepath)
{
if (!file.exists (Zipfilepath))
{
Console.WriteLine ("Cannot find file ' {0} '", Zipfilepath);
Return
}
using (zipinputstream s = new Zipinputstream (File.openread (Zipfilepath)))
{
ZipEntry Theentry;
while ((Theentry = S.getnextentry ())!= null)
{
Console.WriteLine (Theentry.name);
String directoryname = Path.getdirectoryname (theentry.name);
string filename = Path.getfilename (theentry.name);
//Create directory
if (directoryname.length > 0)
{
directory.createdirectory (directoryname);
}
if (filename!= string.empty)
{
using (FileStream streamwriter = File.create (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
}
}
}
}
}
}
}
}
}
Although many popular online compressed file formats are RAR, but because RAR is not an open standard, so zip has become more people's choice. If you don't want to develop your own, you can choose Open source projects, such as SharpZipLib is a good choice