使用SharpCompress解压压缩包以及目录里的压缩包

最近需要解压缩文件,于是用到了这个库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));
              
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值