public class SharpCompressHelper { public static void UnRAR(string srcUrl,string targetUrl) { using (Stream stream = File.OpenRead(srcUrl)) { var reader = ReaderFactory.Open(stream); while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { SharpCompress.Common.ExtractionOptions option = new ExtractionOptions() { Overwrite = true , ExtractFullPath =true}; reader.WriteEntryToDirectory(targetUrl, option); } } } } /// <summary> /// 压缩文件夹 /// </summary> /// <param name="targetFile">压缩文件夹路径</param> /// <param name="zipFile">压缩后路径</param> public void Zips(string targetFile, string zipFile) { using (var archive = ZipArchive.Create()) { ZipRecursion(targetFile, archive); FileStream fs_scratchPath = new FileStream(zipFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); byte[] bytes = new byte[fs_scratchPath.Length]; fs_scratchPath.Read(bytes, 0, bytes.Length); fs_scratchPath.Close(); MemoryStream ms = new MemoryStream(bytes); archive.SaveTo(ms, CompressionType.GZip); fs_scratchPath.Close(); fs_scratchPath.Dispose(); } } /// <summary> /// 压缩递归 /// </summary> /// <param name="fullName">压缩文件夹目录</param> /// <param name="archive">压缩实体</param> public void ZipRecursion(string fullName, ZipArchive archive) { DirectoryInfo di = new DirectoryInfo(fullName);//获取需要压缩的文件夹信息 foreach (var fi in di.GetDirectories()) { if (Directory.Exists(fi.FullName)) { ZipRecursion(fi.FullName, archive); } } foreach (var f in di.GetFiles()) { archive.AddEntry(f.FullName, f.OpenRead());//添加文件夹中的文件 } } }