c# 文件压缩DotNetZip和SharpZipLib
SharpZipLib 和 DotNetZip
DotNetZip示例
using System; using System.IO; using Ionic.Zip; class Program { static void Main(string[] args) { string folderToCompress = @"C:\path\to\your\folder"; // 要压缩的文件夹路径 string zipFilePath = @"C:\path\to\your\zipfile.zip"; // 压缩文件存储路径 using (ZipFile zip = new ZipFile(Encoding.Default))//encodeing.default访止目录下有中文压缩后成乱码 { zip.AddDirectory(folderToCompress, ""); // 添加文件夹到压缩文件,第二个参数为压缩后的文件夹名称,传入空字符串表示不改变文件夹结构 zip.Save(zipFilePath); // 保存压缩文件 } Console.WriteLine("Folder compressed successfully."); } }
SharpZipLib
using System; using System.IO; using ICSharpCode.SharpZipLib.Zip; public class ZipHelper { public static void ZipDirectory(string folderName, string zipFileName) { using (var zipOutputStream = new ZipOutputStream(File.Create(zipFileName))) { zipOutputStream.SetLevel(6); // 0-9, 9 being the highest level of compression ProcessDirectory(zipOutputStream, folderName, string.Empty); zipOutputStream.Finish(); zipOutputStream.Close(); } } private static void ProcessDirectory(ZipOutputStream zipOutputStream, string path, string subPath) { var directoryPath = Path.Combine(path, subPath); // Adds the path to the zip file, just like windows does // with the folders, maintaing the directory structure zipOutputStream.PutNextEntry(new ZipEntry(Path.GetDirectoryName(directoryPath) + Path.DirectorySeparatorChar)); foreach (var filePath in Directory.GetFiles(directoryPath)) { // Create a zip entry based on the file path zipOutputStream.PutNextEntry(new ZipEntry(filePath.Substring(path.Length + 1))); // Open the file and read its content using (var fileStream = File.OpenRead(filePath)) { // Buffer to read the file byte[] buffer = new byte[4096]; int sourceBytes; do { // Copy the buffer to the zip output stream sourceBytes = fileStream.Read(buffer, 0, buffer.Length); zipOutputStream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } foreach (var directoryName in Directory.GetDirectories(directoryPath)) { ProcessDirectory(zipOutputStream, path, directoryName.Substring(path.Length + 1)); } } } // 使用方法: // ZipHelper.ZipDirectory("要压缩的文件夹路径", "输出的压缩文件路径.zip");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2023-05-28 Visual Studio 扩展