我使用的是SharpZipLib的压缩解压库,链接我就不提供了,下载引用就好了
关于压缩,啥也不说,直接先来代码(我的代码基本你可以直接拿去用,我都写成静态函数不用实例化)
压缩类
public static class ZipClass { public static void ZipFileMain(string[] args) { string[] filenames = Directory.GetFiles(args[0]); Crc32 crc = new Crc32(); 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(Path.GetFileName(file)); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. 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(); Directory.Delete(args[0], true); } }
关于参数的说明:ZipFileMain的参数是string[],第一个参数是压缩文件夹路径,第二个是压缩文件路径
解压缩
public static class UnZipClass { public static void UnZip(string[] args) { ZipInputStream s = new ZipInputStream(File.OpenRead(args[0])); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(args[1]); string fileName = Path.GetFileName(theEntry.Name); //生成解压目录 Directory.CreateDirectory(directoryName); if (fileName != String.Empty) { //解压文件到指定的目录 FileStream streamWriter = File.Create(args[1] + 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(); File.Delete(args[0]); } }
关于参数的说明:UnZip的参数是string[],第一个参数是压缩文件路径,第二个是压缩文件夹路径!
新人发帖,顶顶,大家多加我好友,交流交流技术,各位博客园大神多多指教!