封装了一个类,方便使用SevenZipSharp,支持加入进度显示事件。

双重加密压缩工具范例:

using SevenZip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProcessItems
{
    class SevenZipSharpUser
    {
        // 假设这是某个类中的一个事件定义
        public  event EventHandler<ProgressEventArgs> ProgressUpdated = null;

        public static string sInnerSuffix { get; set; } = ".7zx";
        public static CompressionLevel CompLevel { get; set; } = CompressionLevel.Normal;

        public  static bool SetSetLibraryPath()
        {
            //设置库路径
            string currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string dllPath = GetAppropriate7zDllPath(currentDirectory);

            if (!File.Exists(dllPath))
            {
                return false;
            }

            SevenZipSharpUser.SetSetLibraryPath(dllPath);

            return true;
        }

        public static void SetSetLibraryPath(string s7zDllPath)
        {
            SevenZipBase.SetLibraryPath(s7zDllPath);
        }

        public bool CompressItem(string inputItem, string outputFile, string password = null)
        {
            string directory = Path.GetDirectoryName(outputFile);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            if (Directory.Exists(inputItem))
            {
                return CompressDir(inputItem, outputFile, password);
            }
            else if (File.Exists(inputItem))
            {
                return CompressFile(inputItem, outputFile, password);
            }

            return false;
        }

        public bool DoubleCompressItem(string inputItem, string outputFile, string password1 = null, string password2 = null)
        {
            string directory = Path.GetDirectoryName(outputFile);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputFile);

            string sFirstDstPath = Path.Combine(directory, $"{fileNameWithoutExtension}{$"{sInnerSuffix}"}");

            CompressItem(inputItem, sFirstDstPath, password1);
            CompLevel = CompressionLevel.None; //第二层压缩采用存储
            CompressItem(sFirstDstPath, outputFile, password2);

            File.Delete(sFirstDstPath);

            return false;
        }

        public bool ExtractItem(string inputItem, string outputDir, string password = null)
        {
            // 确保输出目录存在
            string directory = Path.GetDirectoryName(outputDir);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            // 检查输入文件是否存在
            if (!File.Exists(inputItem))
            {
                Console.WriteLine($"输入文件不存在: {inputItem}");
                return false;
            }

            try
            {
                // 使用 SevenZipExtractor 打开 .7z 文件
                if (string.IsNullOrEmpty(password))
                {
                    using (var extractor = new SevenZipExtractor(inputItem))
                    {
                        // 提取所有文件到输出目录
                        extractor.ExtractArchive(outputDir);
                    }
                }
                else
                {
                    using (var extractor = new SevenZipExtractor(inputItem, password))
                    {
                        // 提取所有文件到输出目录
                        extractor.ExtractArchive(outputDir);
                    }
                }

                // 解压成功
                return true;
            }
            catch (Exception ex)
            {
                // 处理异常,例如密码错误或文件损坏
                Console.WriteLine($"解压文件时发生错误: {ex.Message}");
                return false;
            }
        }

        public static bool TryPassword(string archivePath, string password)
        {
            try
            {
                using (var extractor = string.IsNullOrEmpty(password)
                       ? new SevenZipExtractor(archivePath) // 无密码
                       : new SevenZipExtractor(archivePath, password)) // 有密码
                {
                    // 检查压缩包中是否有文件
                    if (extractor.ArchiveFileData.Count == 0)
                    {
                        Console.WriteLine("The archive is empty.");
                        return false;
                    }

                    // 尝试解压第一个文件到内存流(不写入磁盘)
                    var fileData = extractor.ArchiveFileData[0];
                    using (var memoryStream = new MemoryStream())
                    {
                        extractor.ExtractFile(fileData.Index, memoryStream);
                    }

                    // 如果没有抛出异常,说明密码正确
                    return true;
                }
            }
            catch (Exception ex)
            {
                // 如果密码错误,会抛出异常
                return false;
            }
        }

        public string GetUniqueFilePath(string filePath)
        {
            string directory = Path.GetDirectoryName(filePath);
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
            string extension = Path.GetExtension(filePath);

            int counter = 1;
            string newFilePath = filePath;

            while (File.Exists(newFilePath))
            {
                newFilePath = Path.Combine(directory, $"{fileNameWithoutExtension}{counter}{extension}");
                counter++;
            }

            return newFilePath;
        }

        public bool CompressFile(string inputFile, string outputFile, string password = null)
        {
            try
            {
                // 检查输入文件是否存在
                if (!File.Exists(inputFile))
                {
                    throw new FileNotFoundException("输入文件不存在。", inputFile);
                }

                // 创建 SevenZipCompressor 实例
                var compressor = new SevenZipCompressor();
                // 设置压缩级别和档案格式
                compressor.EncryptHeaders = true; //加密文件名
                compressor.CompressionLevel = CompLevel;
                compressor.ArchiveFormat = OutArchiveFormat.SevenZip;

                // 订阅进度更新事件
                if (ProgressUpdated != null)
                {
                    compressor.Compressing += ProgressUpdated;
                }

                // 压缩文件
                compressor.CompressFilesEncrypted(outputFile, password, inputFile);

                if (ProgressUpdated != null)
                {
                    compressor.Compressing -= ProgressUpdated;
                }

                // 压缩成功后返回 true
                return true;
            }
            catch (Exception ex)
            {
                // 在发生异常时记录日志、抛出异常或返回 false
                // 这里简单地返回 false,但你可以根据需要更改此行为
                Console.WriteLine($"压缩文件时发生错误: {ex.Message}");
                return false;
            }
            finally
            {

            }
        }

        public bool CompressDir(string stInputDir, string stOutputFile, string stPwd)
        {
            try
            {
                // 检查输入文件是否存在
                if (!Directory.Exists(stInputDir))
                {
                    throw new FileNotFoundException("输入目录不存在。", stInputDir);
                }

                // 创建 SevenZipCompressor 实例
                var compressor = new SevenZipCompressor();
                // 设置压缩级别和档案格式
                compressor.EncryptHeaders = true; //加密文件名
                compressor.CompressionLevel = CompLevel;
                compressor.ArchiveFormat = OutArchiveFormat.SevenZip;

                // 订阅进度更新事件
                if (ProgressUpdated != null)
                {
                    compressor.Compressing += ProgressUpdated;
                }

                // 压缩文件
                compressor.CompressDirectory(stInputDir, stOutputFile, stPwd);

                if (ProgressUpdated != null)
                {
                    compressor.Compressing -= ProgressUpdated;
                }

                // 压缩成功后返回 true
                return true;
            }
            catch (Exception ex)
            {
                // 在发生异常时记录日志、抛出异常或返回 false
                // 这里简单地返回 false,但你可以根据需要更改此行为
                Console.WriteLine($"压缩文件时发生错误: {ex.Message}");
                return false;
            }
            finally
            {

            }
        }

        private static string GetAppropriate7zDllPath(string basePath)
        {
            string dllName = "7z.dll";
            string dllPath = Path.Combine(basePath, dllName);

            // Check if the system is 64-bit or 32-bit
            if (Environment.Is64BitOperatingSystem)
            {
                // If the system is 64-bit, check for a specific 64-bit version of the DLL
                string dll64Path = Path.Combine(basePath, "x64/7z.dll"); // Example name for 64-bit version
                if (File.Exists(dll64Path))
                {
                    return dll64Path;
                }
                // If the specific 64-bit version is not found, fall back to the generic name
            }
            else
            {
                // If the system is 32-bit, check for a specific 32-bit version of the DLL
                string dll32Path = Path.Combine(basePath, "x86/7z.dll"); // Example name for 32-bit version
                if (File.Exists(dll32Path))
                {
                    return dll32Path;
                }
                // If the specific 32-bit version is not found, fall back to the generic name
            }

            // If neither specific version is found, return the generic DLL name (which might be a universal version or an error)
            return dllPath;
        }
    }
}

使用方法:

            //设置库
            if (!SevenZipSharpUser.SetSetLibraryPath())
            {
                MessageBox.Show("7z.dll库引用失败!", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //这里是处理任务逻辑开始========start===========
            if (itemInfo.bDoubleCompress)
            {
                szu.DoubleCompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1, itemInfo.sPassword2);
            }
            else
            {
                szu.CompressItem(itemInfo.sItemPath, itemInfo.sDstPath, itemInfo.sPassword1);
            }

            //这里是处理任务逻辑结束========end=============

更多推荐