C#使用7z进行文件压缩/解压缩

C#使用7z进行文件压缩/解压缩

引言

7z是一种主流高效的压缩格式,它拥有极高的压缩比。下面我来介绍下如何在C#中使用7z.dll进行文件的压缩与解压缩。

1.引用开源库

SevenZipSharp

开源地址https://github.com/tomap/SevenZipSharp

2.代码封装

public static class SevenZipHelper
{
    static SevenZipHelper()
    {
        // 设置7z.dll所在路径
        var path = "bin/7z.dll";
        if (File.Exists(path))
        {
            path = Path.GetFullPath(path);
        }

        SevenZipExtractor.SetLibraryPath(path);
    }

    /// <summary>
    /// 解压
    /// </summary>
    /// <param name="archiveFilePath">压缩包路径</param>
    /// <param name="outputDirectoryPath">输出路径</param>
    /// <param name="password">密码</param>
    public static void ExtractFile(string archiveFilePath, string outputDirectoryPath, string password = "")
    {
        if (!Directory.Exists(outputDirectoryPath))
            Directory.CreateDirectory(outputDirectoryPath);

        using (SevenZipExtractor sZipExtr = new SevenZipExtractor(archiveFilePath))
        {
            sZipExtr.Extracting += ((s, e) =>
            {
            });

            sZipExtr.FileExtractionStarted += ((s, e) =>
            {
            });

            sZipExtr.FileExists += ((s, e) =>
            {
            });

            sZipExtr.ExtractionFinished += ((s, e) =>
            {
            });

            sZipExtr.ExtractArchive(outputDirectoryPath);
        }
    }

    /// <summary>
    /// 压缩
    /// </summary>
    /// <param name="directory">需要压缩的文件夹路径</param>
    /// <param name="archiveFilePath">压缩包的路径</param>
    /// <param name="password">密码</param>
    public static void CompressFile(string directory, string archiveFilePath, string password = "")
    {
        var outDir = Path.GetDirectoryName(archiveFilePath);
        if (!Directory.Exists(outDir))
            Directory.CreateDirectory(outDir);

        SevenZipCompressor cmp = new SevenZipCompressor();
        cmp.ArchiveFormat = OutArchiveFormat.SevenZip;
        cmp.CompressionLevel = CompressionLevel.Ultra;
        cmp.CompressDirectory(directory, archiveFilePath);
    }
}

3.代码调用

压缩文件夹

SevenZipHelper.CompressFile("test", "test.7z");

解压

SevenZipHelper.ExtractFile("test.7z", "test");

注: 原作者的库只支持.Net 4.5,需要.Net Core版本的可以在Nuget上找找,有修改版

posted @ 2024-06-21 10:55  DriftingLeaf  阅读(203)  评论(2编辑  收藏  举报