C#:使用zip压缩 文件 / 文件夹

前置引用:


using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip;

代码实例:


// 打包为 zip
Zip(@"C:\打包的路径", @"D:\目标路径的zip文件.zip");

其余部分:


        public static void Zip(string folderToZip, string zipedFile)
        {
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\" + zipedFile));
            // 设置压缩率
            // zipStream.SetLevel(4);
            ZipDirectory(folderToZip, zipStream);
            zipStream.Finish();
            zipStream.Close();
        }

        public static void ZipDirectory(string folderToZip, ZipOutputStream zipStream)
        {
            string[] folders, files;
            FileStream fs = null;
            Crc32 crc = new Crc32();

            files = Directory.GetFiles(folderToZip);
            foreach (string file in files)
            {
                fs = File.OpenRead(file);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                ZipEntry ent = new ZipEntry(file.Replace(Path.GetDirectoryName(root_dir) + @"\", ""));
                ent.DateTime = DateTime.Now;
                ent.Size = fs.Length;
                fs.Close();
                crc.Reset();
                crc.Update(buffer);
                ent.Crc = crc.Value;
                zipStream.PutNextEntry(ent);
                zipStream.Write(buffer, 0, buffer.Length);
            }
            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }
            GC.Collect();
            GC.Collect(1);

            folders = Directory.GetDirectories(folderToZip);
            foreach (string folder in folders)
            {
                ZipDirectory(folder, zipStream);
            }
        }

你可能感兴趣的:(C#:使用zip压缩 文件 / 文件夹)