C# 使用原生 System.IO.Compression 实现 zip 的压缩与解压

科技资讯 投稿 17300 0 评论

C# 使用原生 System.IO.Compression 实现 zip 的压缩与解压

我们采用的是 微软官方的实现,所以也不需要安装第三方的组件包。

using System.IO.Compression;
/// <summary>
/// 将指定目录压缩为Zip文件
/// </summary>
/// <param name="folderPath">文件夹地址 D:/1/ </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
public static void CompressDirectoryZip(string folderPath, string zipPath
{
    DirectoryInfo directoryInfo = new(zipPath;

    if (directoryInfo.Parent != null
    {
        directoryInfo = directoryInfo.Parent;
    }

    if (!directoryInfo.Exists
    {
        directoryInfo.Create(;
    }

    ZipFile.CreateFromDirectory(folderPath, zipPath, CompressionLevel.Optimal, false;
}

其中 CompressionLevel 是个枚举,支持下面四种类型

枚举注解
Optimal0压缩操作应以***方式平衡压缩速度和输出大小。
Fastest1即使结果文件未可选择性地压缩,压缩操作也应尽快完成。
NoCompression2该文件不应执行压缩。
SmallestSize3压缩操作应尽可能小地创建输出,即使该操作需要更长的时间才能完成。
/// <summary>
/// 将指定文件压缩为Zip文件
/// </summary>
/// <param name="filePath">文件地址 D:/1.txt </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
public static void CompressFileZip(string filePath, string zipPath
{

    FileInfo fileInfo = new FileInfo(filePath;
    string dirPath = fileInfo.DirectoryName?.Replace("\\", "/" + "/";
    string tempPath = dirPath + Guid.NewGuid( + "_temp/";
    if (!Directory.Exists(tempPath
    {
        Directory.CreateDirectory(tempPath;
    }
    fileInfo.CopyTo(tempPath + fileInfo.Name;
    CompressDirectoryZip(tempPath, zipPath;
    DirectoryInfo directory = new(path;
    if (directory.Exists
    {
        //将文件夹属性设置为普通,如:只读文件夹设置为普通
        directory.Attributes = FileAttributes.Normal;

        directory.Delete(true;
    }
}

压缩单个文件的逻辑其实就是先将我们要压缩的文件复制到一个临时目录,然后对临时目录执行了压缩动作,压缩完成之后又删除了临时目录。

/// <summary>
/// 解压Zip文件到指定目录
/// </summary>
/// <param name="zipPath">zip地址 D:/1.zip</param>
/// <param name="folderPath">文件夹地址 D:/1/</param>
public static void DecompressZip(string zipPath, string folderPath
{
    DirectoryInfo directoryInfo = new(folderPath;

    if (!directoryInfo.Exists
    {
        directoryInfo.Create(;
    }

    ZipFile.ExtractToDirectory(zipPath, folderPath;
}

至此 C# 使用原生 System.IO.Compression 实现 zip 的压缩与解压 就讲解完了,有任何不明白的,可以在文章下面评论或者私信我,欢迎大家积极的讨论交流,有兴趣的朋友可以关注我目前在维护的一个 .NET 基础框架项目,项目地址如下
https://github.com/berkerdong/NetEngine.git
https://gitee.com/berkerdong/NetEngine.git

编程笔记 » C# 使用原生 System.IO.Compression 实现 zip 的压缩与解压

赞同 (36) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽