C# 压缩或解压

代码来源网上,经过了我的稍微改造,方便后面我的使用,如果能帮到你,当然更好。

首先,你需要安装SharpZipLib

<PackageReference Include="SharpZipLib" Version="1.3.3" />
public class ZipHelper
{
    public static ZipHelper Default { get; } = new ZipHelper();
    public int CompressionLevel { get; set; } = 6;
    public void Zip(string savePath, IEnumerable<string> paths)
    {
        ZipOutputStream zipStream;
        using (zipStream = new ZipOutputStream(File.Create(savePath)))
        {
            zipStream.SetLevel(6); //设置CompressionLevel,压缩比
            foreach (string f in paths)
            {
                ZipMultiFiles(f, zipStream);//压缩
            }
        }
    }

    public Task ZipAsync(string savePath, IEnumerable<string> paths)
    {
        return Task.Run(() =>
         {
             this.Zip(savePath, paths);
         });
    }

    public void UnZip(string sourceFile, string targetDir)
    {
        using (ZipInputStream InzipStream = new ZipInputStream(File.OpenRead(sourceFile)))
        {
            UnZipMultiFiles(sourceFile, InzipStream, targetDir);
        }
    }

    public Task UnZipAsync(string sourceFile, string targetDir)
    {
        return Task.Run(() =>
         {
             this.UnZip(sourceFile, targetDir);
         });
    }

    private void ZipMultiFiles(string file, ZipOutputStream zipStream, string lastName = "")
        {
            if (File.Exists(file))      //是文件,压缩  
            {
                FileStream streamReader;
                using (streamReader = File.OpenRead(file))
                {
                    //处理file,如果不处理,直接new ZipEntry(file)的话,压缩出来是全路径
                    //如C:\Users\RD\Desktop\image\001.xml,压缩包里就是C:\Users\RD\Desktop\image\001.xml
                    //如果处理为image\001.xml压缩出来就是image\001.xml(这样才跟用工具压缩的是一样的效果)
                    string path = Path.GetFileName(file);
                    if (lastName != "")
                    {
                        path = lastName + "\\" + path;
                    }
                    ZipEntry zipEntry = new ZipEntry(path);
                    zipEntry.DateTime = DateTime.Now;
                    zipEntry.Size = streamReader.Length;

                    zipStream.PutNextEntry(zipEntry);//压入
                    byte[] buffer = new byte[4096 * 1024];
                    int sourceCount;
                    while ((sourceCount = streamReader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipStream.Write(buffer, 0, sourceCount);
                    }
                }
            }
            else//是文件夹,递归
            {
                string[] filesArray = Directory.GetFileSystemEntries(file);
                string folderName = Regex.Match(file, @"[^\/:*\?\”“\<>|,\\]*$").ToString();//获取最里一层文件夹
                if (lastName != "")
                {
                    folderName = lastName + "\\" + folderName;
                }
                if (filesArray.Length == 0)//如果是空文件夹
                {
                    ZipEntry zipEntry = new ZipEntry(folderName + "/");//加/才会当作文件夹来压缩
                    zipStream.PutNextEntry(zipEntry);
                }
                foreach (string f in filesArray)
                {
                    ZipMultiFiles(f, zipStream, folderName);
                }
            }
        }

    private void UnZipMultiFiles(string file, ZipInputStream zipStream, string unzippath)
        {
            ZipEntry theEntry;
            while ((theEntry = zipStream.GetNextEntry()) != null)
            {
                string fileName = Path.GetFileNameWithoutExtension(file);
                string entryName = theEntry.Name.Replace(":", "_");//如果路径里有盘符 如C: 解压后应为名为C_的文件夹来代表盘符
                string directoryName = Path.Combine(unzippath, entryName);
                //建立下面的目录和子目录  
                if (!Directory.Exists(Path.GetDirectoryName(directoryName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(directoryName));
                }
                string name = directoryName.Replace('/', '\\');//如果为空文件
                if (name.EndsWith("\\"))
                {
                    continue;
                }
                using (FileStream streamWriter = File.Create(directoryName))
                {
                    int sourceCount = 0;
                    byte[] buffer = new byte[4096 * 1024];
                    while ((sourceCount = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        streamWriter.Write(buffer, 0, sourceCount);
                    }
                }
            }
        }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若汝棋茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值