.NET Core(C#)使用SharpCompress压缩解压文件(.rar,.zip,tar.bz2,.7z,.tar.gz)
一、SharpCompress 库简介
.NET Core中使用SharpCompress库可以方便地进行多种格式的文件压缩和解压缩操作,支持的格式包括.rar, .zip, .tar.bz2, .7z, .tar.gz 等。
SharpCompress是一个开源的.NET库,提供了对多种压缩格式的读写支持。
本文主要介绍.NET Core(C#)使用sharpcompress压缩文件(.zip,.tar.bz2,.tar.gz)的代码以解压(.rar,.zip,.7z)的代码。
SharpCompress支持的格式:
源码地址:
https://gitcode.com/gh_mirrors/sh/sharpcompress
Install-Package SharpCompress
二、使用案例
/// <summary> /// 文件压缩解压缩处理 /// </summary> public class CompressHelper { public static string RootPath { get { return FreeSpireHelper.RootPath; } } public static string CompressPath { get { string path = FreeSpireHelper.RootPath + "/comprestemp/"; if (Directory.Exists(path) == false) Directory.CreateDirectory(path); return path; } } #region Rar /// <summary> /// 解压缩rar文件---目前不支持rar压缩 /// </summary> /// <param name="file"></param> #endregion #region Zip /// <summary> /// 压缩zip文件,指定文件夹,全部压缩 /// </summary> /// <param name="path"></param> public static void CompressZip(string path) { DirectoryInfo dir = new DirectoryInfo(path); string filename = path + ".zip"; using (var zip = File.OpenWrite(filename)) using (var zipWriter = WriterFactory.Open(zip, ArchiveType .Zip, CompressionType.Deflate)) { zipWriter.WriteAll(path, "*", SearchOption.AllDirectories); } } #endregion #region 7z /// <summary> /// 7z解压缩----目前不支持7z压缩 /// </summary> /// <param name="filename"></param> #endregion #region 通用方法 /// <summary> /// 通用解压 rar,zi,7z,tar等 /// </summary> /// <param name="filename"></param> public static List<string> DeCompress(string filename) { List<string> result = new List<string>(); filename = RootPath + filename; FileInfo file = new FileInfo(filename); if (file.Exists == false) throw new Exception("压缩文件不存在"); var archive = ArchiveFactory.Open(filename); foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { //Console.WriteLine(entry.Key); string path = CompressPath + file.Name.Substring(0, file.Name.LastIndexOf(".")); if (Directory.Exists(path) == false) Directory.CreateDirectory(path); entry.WriteToDirectory(path, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true }); result.Add((path+ "/"+ entry.Key).Replace(RootPath, "")); } } return result; } #endregion }
测试代码:
//文件压缩解压 //List<string> result=CompressHelper.DeCompress("5.zip"); ////CompressHelper.DeCompress("2.7z"); ////List<string> result=CompressHelper.DeCompress("3.tar"); ////List<string> result = CompressHelper.DeCompress("202504.rar"); //foreach (string s in result) { // Console.WriteLine( s); //} CompressHelper.CompressZip("G:\\QLTest\\Core_Solution\\Dotnet8\\PDFTest\\PDFTest\\bin\\Debug\\net8.0\\comprestemp\\202504");
三、文章来源:
https://www.cjavapy.com/article/343/
更多:
.Net Core HTML/JS/CSS 静态文件压缩方案,YUICompressor.NET