namespace SharpCompressStudy.Core { /// /// 因为:Rar压缩算法是私有的,而解压文件算法是公开的。 /// 所以:不能创建Rar压缩文件,但能解压现有Rar文件。 /// 能解压和创建zip、tar、7z等压缩格式的文件 /// public class WinRarFileTest:IDisposable { private readonly ITestOutputHelper testOutput; public WinRarFileTest(ITestOutputHelper testOutputHelper) { this.testOutput = testOutputHelper; } /// /// 解压Rar文件 /// 注意:不能创建Rar压缩文件 /// [Fact] public void ExtractFromRar_Test() { var rarFilePath = AppDomain.CurrentDomain.BaseDirectory + "Resource\\学习2.rar"; if (!File.Exists(rarFilePath)) { throw new FileNotFoundException("Rar文件不存在"); } //扩展名 var extName = Path.GetExtension(rarFilePath); //文件名 var rarFileName = Path.GetFileName(rarFilePath).Replace(extName, ""); //不带扩展名的文件名 var rarFileNameWithoutExt = Path.GetFileNameWithoutExtension(rarFilePath); //解压根目录 var extractPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource\\models\\temp\\", Guid.NewGuid().ToString() + "\\"); using (var archive = RarArchive.Open(rarFilePath)) { //压缩文件是否包含同名根目录(abc.rar解决后是否有一个名为abc的根目录) if (archive.Entries.Where(f => f.IsDirectory && f.Key == rarFileNameWithoutExt).Count() != 1) { extractPath = Path.Combine(extractPath, rarFileNameWithoutExt); } //创建解压目录 if (!Directory.Exists(extractPath)) { Directory.CreateDirectory(extractPath); } //解压所有文件到指定目录 foreach (var entry in archive.Entries) { if (!entry.IsDirectory) { entry.WriteToDirectory(extractPath, new ExtractionOptions { ExtractFullPath = true, Overwrite = true }); } } } testOutput.WriteLine($"文件解压到目录:{extractPath}"); } [Fact] public void CompressToZip_Test() { string filesPath = AppDomain.CurrentDomain.BaseDirectory + "Resource\\学习"; var extractPathFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource\\", Guid.NewGuid().ToString() + "\\"); var extractPathFile = Path.Combine(extractPathFolder, "学习.zip"); if (!Directory.Exists(extractPathFolder)) { Directory.CreateDirectory(extractPathFolder); } using var zip = File.OpenWrite(extractPathFile); using var zipWriter = WriterFactory.Open(zip, ArchiveType.Zip, CompressionType.Deflate); zipWriter.WriteAll(filesPath, "*", SearchOption.AllDirectories); } public void Dispose() { GC.SuppressFinalize(this); } } }