C#使用SharpZipLib对文件进行压缩和解压

C#使用SharpZipLib对文件进行压缩和解压

使用SharpZipLib库

编写SharpZipLibHelper帮助类

using ICSharpCode.SharpZipLib.Zip;

namespace SharpZipLib_Project
{
    public class SharpZipLibHelper
    {
        /// <summary>
        /// 多个文件或文件夹压缩
        /// </summary>
        /// <param name="sourcePaths">文件或文件夹名称</param>
        /// <param name="zipFilePath">压缩文件夹名称</param>
        public static string CompressFilesAndDirectories(string[] sourcePaths, string zipFilePath)
        {
            try
            {
                using (FileStream fsOut = File.Create(zipFilePath))
                {
                    using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
                    {
                        foreach (string sourcePath in sourcePaths)
                        {
                            if (Directory.Exists(sourcePath))
                            {
                                CompressDirectoryRecursive(sourcePath, zipStream);
                            }
                            else if (File.Exists(sourcePath))
                            {
                                CompressFile(sourcePath, zipStream);
                            }
                            else
                            {
                                Console.WriteLine($"Path '{sourcePath}' does not exist.");
                            }
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 向压缩文件添加文件
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="zipStream"></param>
        /// <returns></returns>
        private static string CompressFile(string sourceFilePath, ZipOutputStream zipStream)
        {
            try
            {
                string entryName = Path.GetFileName(sourceFilePath);
                ZipEntry newEntry = new ZipEntry(entryName);
                zipStream.PutNextEntry(newEntry);

                byte[] buffer = new byte[4096];
                using (FileStream fsIn = File.OpenRead(sourceFilePath))
                {
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fsIn.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, sourceBytes);
                    } while (sourceBytes > 0);
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 向压缩文件添加文件夹
        /// </summary>
        /// <param name="rootDirectoryPath"></param>
        /// <param name="currentDirectoryPath"></param>
        /// <param name="zipStream"></param>
        /// <returns></returns>
        private static string CompressDirectoryRecursive(string sourceDirectoryPath, ZipOutputStream zipStream)
        {
            try
            {
                string[] files = Directory.GetFiles(sourceDirectoryPath, "*", SearchOption.AllDirectories);
                string rootDirectoryName = Path.GetFileName(sourceDirectoryPath);

                // 添加文件夹本身
                ZipEntry rootDirectoryEntry = new ZipEntry(rootDirectoryName + "/");
                zipStream.PutNextEntry(rootDirectoryEntry);

                // 添加文件夹内的文件和子文件夹
                foreach (string file in files)
                {
                    string relativePath = Path.GetRelativePath(sourceDirectoryPath, file);
                    ZipEntry newEntry = new ZipEntry(rootDirectoryName + "/" + relativePath);
                    zipStream.PutNextEntry(newEntry);

                    byte[] buffer = new byte[4096];
                    using (FileStream fsIn = File.OpenRead(file))
                    {
                        int sourceBytes;
                        while ((sourceBytes = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            zipStream.Write(buffer, 0, sourceBytes);
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件地址</param>
        /// <param name="extractPath">解压文件夹</param>
        /// <returns></returns>
        public static string DecompressFile(string zipFilePath, string extractPath)
        {
            try
            {
                if (!Directory.Exists(extractPath))
                    Directory.CreateDirectory(extractPath);

                using (FileStream fsIn = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (ZipInputStream zipStream = new ZipInputStream(fsIn))
                    {
                        ZipEntry entry;
                        while ((entry = zipStream.GetNextEntry()) != null)
                        {
                            string entryFileName = Path.Combine(extractPath, entry.Name);
                            string directoryName = Path.GetDirectoryName(entryFileName);

                            if (directoryName.Length > 0 && !Directory.Exists(directoryName))
                                Directory.CreateDirectory(directoryName);

                            if (entry.IsFile)
                            {
                                using (FileStream fsOut = File.Create(entryFileName))
                                {
                                    byte[] buffer = new byte[4096];
                                    int sourceBytes;
                                    while ((sourceBytes = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fsOut.Write(buffer, 0, sourceBytes);
                                    }
                                }
                            }
                        }
                    }
                }
                return "成功";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}

如何使用工具类

private void button1_Click(object sender, EventArgs e)
{
    // 压缩文件
    string[] sourcePaths = { "example.txt", "Example", "example1.txt"};
    string str = SharpZipLibHelper.CompressFilesAndDirectories(sourcePaths, "example.zip");
    if (str != "成功")
    {
        MessageBox.Show($"压缩失败: {str}");
    }
    else
    {
        MessageBox.Show("压缩成功!");
    }
}

private void button2_Click(object sender, EventArgs e)
{
    // 解压缩文件
    string str = SharpZipLibHelper.DecompressFile("example.zip", "extracted_files");
    if (str != "成功")
    {
        MessageBox.Show($"解压失败: {str}");
    }
    else
    {
        MessageBox.Show("解压成功!");
    }
}

备注: 这种压缩方法无法压缩空的文件夹,因为空的文件夹里面没有文件路径,所有会自动忽略.如果需要添加空文件夹需要自己先判断目录是否为空,然后自己在压缩文件中创建就可以了

2024.3.13

相关推荐

  1. C#使用SharpZipLib文件进行压缩和解

    2024-03-17 21:50:05       50 阅读
  2. C# 压缩和解文件文件夹

    2024-03-17 21:50:05       52 阅读
  3. Ubuntu中如何压缩和解文件

    2024-03-17 21:50:05       36 阅读
  4. linux下使用 tar 来压缩和解 tar.gz 和 tar.xz 文件

    2024-03-17 21:50:05       36 阅读
  5. 关于安卓文件夹压缩和解(一)zip处理

    2024-03-17 21:50:05       48 阅读
  6. 在Qt C++项目中调用7z API实现压缩和解

    2024-03-17 21:50:05       20 阅读
  7. linux下tar命令的压缩和解详细使用方法

    2024-03-17 21:50:05       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-17 21:50:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-17 21:50:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-17 21:50:05       87 阅读
  4. Python语言-面向对象

    2024-03-17 21:50:05       96 阅读

热门阅读

  1. C# 入门

    C# 入门

    2024-03-17 21:50:05      35 阅读
  2. ASP.NET

    ASP.NET

    2024-03-17 21:50:05      38 阅读
  3. Linux桌面Cinnamon项目简介

    2024-03-17 21:50:05       39 阅读
  4. uniapp使用腾讯地图获取地址信息

    2024-03-17 21:50:05       37 阅读
  5. go的fasthttp学习~stackless的writer

    2024-03-17 21:50:05       38 阅读
  6. MySQL 索引

    2024-03-17 21:50:05       39 阅读
  7. Qt——智能指针实战

    2024-03-17 21:50:05       45 阅读
  8. spring MVC 自定义注解实现路径匹配

    2024-03-17 21:50:05       42 阅读
  9. qt之画图

    2024-03-17 21:50:05       34 阅读
  10. Spring中的bean相关问题

    2024-03-17 21:50:05       48 阅读