C#压缩指定文件或文件夹

这个功能在某些批量生成的场景会用到,之前有一篇博客写的是批量生成二维码,生成完之后其实是在本机上生成的,发布到服务器上之后,需要下载到客户端,所以把二维码压缩成压缩包然后下载是很有必要的。

首先NuGet下载ICSharpCode.SharpZipLib.dll

然后新建一个ZipHelper类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
//using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Checksum;

namespace Driver.Core.Web
{
    public class ZipHelper
    {
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="destinationZipFilePath"></param>
        public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                sourceFilePath += System.IO.Path.DirectorySeparatorChar;

            ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
            zipStream.SetLevel(6);  // 压缩级别 0-9
            CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);

            zipStream.Finish();
            zipStream.Close();
        }

        /// <summary>
        /// 递归压缩文件
        /// </summary>
        /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
        /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
        /// <param name="staticFile"></param>
        public static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
        {
            Crc32 crc = new Crc32();
            string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
            foreach (string file in filesArray)
            {
                if (Directory.Exists(file))                     //如果当前是文件夹,递归
                {
                    CreateZipFiles(file, zipStream, staticFile);
                }

                else                                            //如果是文件,开始压缩
                {
                    FileStream fileStream = File.OpenRead(file);

                    byte[] buffer = new byte[fileStream.Length];
                    fileStream.Read(buffer, 0, buffer.Length);
                    string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
                    ZipEntry entry = new ZipEntry(tempFile);

                    entry.DateTime = DateTime.Now;
                    entry.Size = fileStream.Length;
                    fileStream.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zipStream.PutNextEntry(entry);
                    zipStream.Write(buffer, 0, buffer.Length);
                }
            }
        }
    }
}

然后调用的时候就很简单了

        public ActionResult GeneralizeBatchStorage()
        {
            try
            {
                //string desktopPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
                string desktopPath = @"D:\DealerQRcode";
                string returntext = DateTime.Now.ToString("yyyyMMddHHmmss") + "二维码下载";
                string newStoragePath = desktopPath + @"\" + returntext;
                Directory.CreateDirectory(newStoragePath);
                DataTable data = CarBindBLL.IsCarDatasUsereseqws();
                List<SysUsersModel> carAndBindModels = ConvertHelper<SysUsersModel>.ConvertToList(data);
                foreach (var item in carAndBindModels)
                {
                    string generalizeUrl = WebConfigurationManager.AppSettings["apiUrl"] + new DesArithmetic().DesEncrypt(item.usr_name);
                    byte[] generalizebyte = ImgToByte(GetCode(generalizeUrl, 8, 7, WebConfigurationManager.AppSettings["icoImg"], 15, 1, false));
                    Image image = Image.FromStream(new MemoryStream(generalizebyte));
                    string imgStoragePath = newStoragePath + @"\" + item.usr_name + ".jpg";
                    image.Save(imgStoragePath, ImageFormat.Jpeg);
                    CodeAddText(item.usr_name, imgStoragePath);
                }
                //压缩文件(文件夹路径,压缩文件名称和存放路径)
                ZipHelper.CreateZip(newStoragePath, newStoragePath + ".zip");
                var returnData = new
                {
                    message = "0",
                    url = WebConfigurationManager.AppSettings["DealerQRcode"] + returntext + ".zip"
                };
                return Json(returnData, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                var returnData = new
                {
                    message = "1",
                    url = ""
                };
                return Json(returnData, JsonRequestBehavior.AllowGet);
            }
        }

这样就完成了整个操作,是不是很简单

THE END