C#文件压缩成.Zip
使用的三方类库ICSharpCode.SharpZipLib.dll
方法如下:
////// 压缩文件为zip格式 /// /// 文件地址 /// 目标路径 static bool CompressFiles(string filePath, string targetPath) { try { using (ZipOutputStream zipstream = new ZipOutputStream(File.Create(targetPath))) { zipstream.SetLevel(9); // 压缩级别 0-9 byte[] buffer = new byte[4096]; //缓冲区大小 ZipEntry entry = new ZipEntry(Path.GetFileName(filePath)); entry.DateTime = DateTime.Now; zipstream.PutNextEntry(entry); using (FileStream fs = File.OpenRead(filePath)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); zipstream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } zipstream.Finish(); zipstream.Close(); return true; } } catch (Exception ex) { return false; } }
压缩文件夹
////// 压缩文件夹 /// /// /// /// public static bool ZipFile(string strFile, string strZip) { try { if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) { strFile += Path.DirectorySeparatorChar; } ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip)); outstream.SetLevel(6); ZipCompress(strFile, outstream, strFile); outstream.Finish(); outstream.Close(); return true; } catch (Exception) { return false; } } public static void ZipCompress(string strFile, ZipOutputStream outstream, string staticFile) { if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) { strFile += Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); //获取指定目录下所有文件和子目录文件名称 string[] filenames = Directory.GetFileSystemEntries(strFile); //遍历文件 foreach (string file in filenames) { if (Directory.Exists(file)) { ZipCompress(file, outstream, staticFile); } //否则,直接压缩文件 else { //打开文件 FileStream fs = File.OpenRead(file); //定义缓存区对象 byte[] buffer = new byte[fs.Length]; //通过字符流,读取文件 fs.Read(buffer, 0, buffer.Length); //得到目录下的文件(比如:D:\Debug1\test),test string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1); ZipEntry entry = new ZipEntry(tempfile); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; outstream.PutNextEntry(entry); //写文件 outstream.Write(buffer, 0, buffer.Length); } } }