SharpCompressStudy/SharpCompressStudy.Test/WinRarFileTest.cs

91 lines
3.2 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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\\学习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);
}
}
}