C# 实现压缩和解压缩文件
开发时经常会遇到需要压缩文件的需求,利用C#的开源组件ICSharpCode.SharpZipLib,
就可以很容易的实现压缩和解压缩功能。
主要是操作(Zip)压缩算法
上代码:
压缩文件
/// <summary> /// 压缩指定文件生成ZIP文件 /// </summary> /// <param name="topDirName">顶层文件夹名称</param> /// <param name="fileNamesToZip">待压缩文件</param> /// <param name="ZipedFileName">ZIP文件</param> /// <param name="CompressionLevel">压缩比</param> /// <param name="password">密码</param> /// <param name="comment">压缩文件注释文字</param> public static void ZipFile ( string topDirName, //顶层文件夹名称 string fileNameToZip, //待压缩文件 string ZipedFileName, //ZIP文件 int CompressionLevel, //压缩比 string password, //密码 string comment //压缩文件注释文字 ) { var ls = new List<string> { fileNameToZip }; ZipFile(topDirName, ls.ToArray(), ZipedFileName, CompressionLevel, password, comment); } /// <summary> /// 压缩指定多个文件生成ZIP文件 /// </summary> /// <param name="topDirName">顶层文件夹名称</param> /// <param name="fileNamesToZip">待压缩文件列表</param> /// <param name="ZipedFileName">ZIP文件</param> /// <param name="CompressionLevel">压缩比</param> /// <param name="password">密码</param> /// <param name="comment">压缩文件注释文字</param> public static void ZipFile ( string topDirName, //顶层文件夹名称 string[] fileNamesToZip, //待压缩文件列表 string ZipedFileName, //ZIP文件 int CompressionLevel, //压缩比 9 string password, //密码 "" string comment //压缩文件注释文字 "" ) { using (var s = new ZipOutputStream(File.Open(ZipedFileName, FileMode.Create))) { if (password != null && password.Length > 0) s.Password = password; if (comment != null && comment.Length > 0) s.SetComment(comment); s.SetLevel(CompressionLevel); // 0 - means store only to 9 - means best compression foreach (string file in fileNamesToZip) { using (FileStream fs = File.OpenRead(topDirName + 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; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); } }
解压缩文件: