|
|
namespace SharpCompressStudy.Core
|
|
|
{
|
|
|
/// <summary>
|
|
|
/// 因为:Rar压缩算法是私有的,而解压文件算法是公开的。
|
|
|
/// 所以:不能创建Rar压缩文件,但能解压现有Rar文件。
|
|
|
/// 能解压和创建zip、tar、7z等压缩格式的文件
|
|
|
/// </summary>
|
|
|
public class WinRarFileTest:IDisposable
|
|
|
{
|
|
|
private readonly ITestOutputHelper testOutput;
|
|
|
public WinRarFileTest(ITestOutputHelper testOutputHelper)
|
|
|
{
|
|
|
this.testOutput = testOutputHelper;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 解压Rar文件
|
|
|
/// 注意:不能创建Rar压缩文件
|
|
|
/// </summary>
|
|
|
[Fact]
|
|
|
public void ExtractFromRar_Test()
|
|
|
{
|
|
|
var rarFilePath = AppDomain.CurrentDomain.BaseDirectory + "Resource\\学习.rar";
|
|
|
|
|
|
var extractPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource\\", Guid.NewGuid().ToString() + "\\");
|
|
|
if (!Directory.Exists(extractPath))
|
|
|
{
|
|
|
Directory.CreateDirectory(extractPath);
|
|
|
}
|
|
|
using (var archive = RarArchive.Open(rarFilePath))
|
|
|
{
|
|
|
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);
|
|
|
}
|
|
|
}
|
|
|
} |