Asp.net在线压缩、解压缩 --- SharpZipLib带来的新视野。 09/07/2006 07:02:34 PM Views: 275 Pictures: 0 很早以前就听说过SharpZipLib的大名了,一直没有关注。 直到最近做Reference Library,需要在线压缩和解压缩Reference Item图片。 我立即想到了这个久闻而未尝接触的开源项目。 下回来看了下文档,大概有了一个初步的了解,记录一下以免忘记。 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; class MainClass { // 在控制命令行下输入要解压的Zip文件名 public static void Main(string[] args) { // 创建读取Zip文件对象 ZipInputStream s = new ZipInputStream(File.OpenRead(args[0])); // Zip文件中的每一个文件 ZipEntry theEntry; // 循环读取Zip文件中的每一个文件 while ((theEntry = s.GetNextEntry()) != null) { Console.WriteLine(theEntry.Name); string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // create directory Directory.CreateDirectory(directoryName); if (fileName != String.Empty) { // 解压文件 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; } } streamWriter.Close(); } } s.Close(); } } -------------------------------------------------------------------------------- using System; using System.IO; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.GZip; class MainClass { // 输入要压缩的文件夹和要创建的Zip文件文件名称 public static void Main(string[] args) { string[] filenames = Directory.GetFiles(args[0]); Crc32 crc = new Crc32(); // 创建输出Zip文件对象 ZipOutputStream s = new ZipOutputStream(File.Create(args[1])); // 设置压缩等级 s.SetLevel(6); // 0 - store only to 9 - means best compression // 循环读取要压缩的文件,写入压缩包 foreach (string file in filenames) { 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; 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(); } }