最近需要解压缩文件,于是用到了这个库SharpCompress,可以使用,但是发现一个问题,这个库并不支持测试密码是否正确,而如果使用try和catch尝试,发现即使密码错误,有时候也能够正确打开文件,所以这个方法也不靠谱,更要命的是性能问题,在解压某些压缩包时,这个库遇到了严重的性能问题,最终不得已还是使用了命令行调用7z.exe解决问题。
不过鉴于这个库还是有意义的,于是在此整理了使用的类。
在这里提供了尝试密码的函数,但是有个问题就是,当7z的格式比较新的时候,此代码无法支持,这种情况下还得用专门的7z.dll尝试。
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Archives.SevenZip;
using SharpCompress.Archives.Zip;
using SharpCompress.Common;
using SharpCompress.Readers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProcessItems
{
class SharpCompressUser
{
public delegate void ReportProgress(int nCurrent, int nTotal);
public ReportProgress reportProgress { get; set; } = null;
private static int _counter = 0;
private bool bReportFileProgress = true;
public bool ExtractFile(string filePath, string sDstDir = "", string password = "")
{
try
{
// 指定解压到的目录,这里使用与RAR文件相同的目录
string extractPath = Path.GetDirectoryName(filePath);
if (sDstDir.Length > 0)
{
if (!Directory.Exists(sDstDir))
{
Directory.CreateDirectory(sDstDir);
}
extractPath = sDstDir;
}
// 打开RAR文件
using (var archive = ArchiveFactory.Open(filePath, new ReaderOptions
{
Password = password
}))
{
int itemCount = archive.Entries.Count();
for (int i = 0; i < itemCount; ++i)
{
var entry = archive.Entries.ElementAt(i);
if (!entry.IsDirectory)
{
// 获取解压后的文件路径
string fullPath = Path.Combine(extractPath, entry.Key);
// 确保目录存在
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));