C# 文件压缩 解压 创建压缩文件 解压文件.zip .rar

一些zip文件操作的工具类,包括
压缩、解压

using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

{
    public class ZipHelper
    {
        /// <summary>
        /// 压缩多个文件目录
        /// </summary>
        /// <param name="dirname">需要压缩的目录</param>
        /// <param name="zipFile">压缩后的文件名</param>
        /// <param name="level">压缩等级</param>
        /// <param name="password">密码</param>
        public static void ZipDir(string dirname, string zipFile, int level = 5, string password = "123")
        {
            ZipOutputStream zos = new ZipOutputStream(File.Create(zipFile));
            zos.Password = password;
            zos.SetLevel(level);
            addZipEntry(dirname, zos, dirname);
            zos.Finish();
            zos.Close();
        }
        /// <summary>
        /// 往压缩文件里面添加Entry
        /// </summary>
        /// <param name="PathStr">文件路径</param>
        /// <param name="zos">ZipOutputStream</param>
        /// <param name="BaseDirName">基础目录</param>
        private static void addZipEntry(string PathStr, ZipOutputStream zos, string BaseDirName)
        {
            DirectoryInfo dir = new DirectoryInfo(PathStr);
            foreach (FileSystemInfo item in dir.GetFileSystemInfos())
            {
                if ((item.Attributes & FileAttributes.Directory) == FileAttributes.Directory)//如果是文件夹继续递归
                {
                    addZipEntry(item.FullName, zos, BaseDirName);
                }
                else
                {
                    FileInfo f_item = (FileInfo)item;
                    using (FileStream fs = f_item.OpenRead())
                    {
                        byte[] buffer = new byte[(int)fs.Length];
                        fs.Position = 0;
                        fs.Read(buffer, 0, buffer.Length);
                        fs.Close();
                        ZipEntry z_entry = new ZipEntry(item.FullName.Replace(BaseDirName, ""));
                        zos.PutNextEntry(z_entry);
                        zos.Write(buffer, 0, buffer.Length);
                    }
                }
            }
        }

        #region 压缩多个文件

        /// <summary>
        ///  压缩多个文件
        /// </summary>
        /// <param name="files">文件名</param>
        /// <param name="ZipedFileName">压缩包文件名</param>
        /// <param name="Password">解压码</param>
        /// <returns></returns>
        public static void Zip(string[] files, string ZipedFileName, string Password)
        {
            files = files.Where(f => File.Exists(f)).ToArray();
            if (files.Length == 0) throw new FileNotFoundException("未找到指定打包的文件");
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFileName));
            s.SetLevel(6);
            if (!string.IsNullOrEmpty(Password.Trim())) s.Password = Password.Trim();
            ZipFileDictory(files, s);
            s.Finish();
            s.Close();
        }

        /// <summary>
        ///  压缩多个文件
        /// </summary>
        /// <param name="files">文件名</param>
        /// <param name="ZipedFileName">压缩包文件名</param>
        /// <returns></returns>
        public static void Zip(string[] files, string ZipedFileName)
        {
            Zip(files, ZipedFileName, string.Empty);
        }

        private static void ZipFileDictory(string[] files, ZipOutputStream s)
        {
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                //创建当前文件夹
                entry = new ZipEntry("/");  //加上 “/” 才会当成是文件夹创建
                s.PutNextEntry(entry);
                s.Flush();
                foreach (string file in files)
                {
                    //打开压缩文件
                    fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry("/" + Path.GetFileName(file));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                    entry = null;
                GC.Collect();
            }
        }

        /// <summary>
        /// 递归压缩传入压缩流路径和输出流路径
        /// </summary>
        /// <param name="sourceFilePath">待压缩文件/文件夹完整物理路径</param>
        /// <param name="destinationZipFilePath">压缩后文件完整物理路径</param>
        /// <param name="NoCompressFileName">排除待压缩文件夹路径下的文件:不压缩</param>
        public static void CreateZip(string sourceFilePath, string destinationZipFilePath)//, string NoCompressFileName
        {
            if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                sourceFilePath += System.IO.Path.DirectorySeparatorChar;
            ZipOutputStream zipStream;
            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>
        private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)//, string NoCompressFileName
        {
            Crc32 crc = new Crc32();
            string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
            foreach (string file in filesArray)
            {
                if (Directory.Exists(file))//如果当前是文件夹,递归
                {
                    CreateZipFiles(file, zipStream, staticFile);
                }
                else//如果是文件,开始压缩
                {
                    using (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();
                        //fileStream.Dispose();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        zipStream.PutNextEntry(entry);
                        zipStream.Write(buffer, 0, buffer.Length);
                    }
                        
                }
            }
        }

        #endregion 压缩多个文件

        #region 解压文件 包括.rar 和zip

        /// <summary>
        ///解压文件
        /// </summary>
        /// <param name="fileFromUnZip">解压前的文件路径(绝对路径)</param>
        /// <param name="fileToUnZip">解压后的文件目录(绝对路径)</param>
        public static void UnpackFileRarOrZip(string fileFromUnZip, string fileToUnZip)
        {
            //获取压缩类型
            string unType = fileFromUnZip.Substring(fileFromUnZip.LastIndexOf(".") + 1, 3).ToLower();

            switch (unType)
            {
                case "rar":
                    UnRar(fileFromUnZip, fileToUnZip);
                    break;

                default:
                    UnZip(fileFromUnZip, fileToUnZip);
                    break;
            }
        }

        #endregion 解压文件 包括.rar 和zip

        #region 解压文件 .rar文件

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="unRarPatch"></param>
        /// <param name="rarPatch"></param>
        /// <param name="rarName"></param>
        /// <returns></returns>
        public static void UnRar(string fileFromUnZip, string fileToUnZip)
        {
            string the_rar;
            RegistryKey the_Reg;
            object the_Obj;
            string the_Info;

            try
            {
                the_Reg = Registry.LocalMachine.OpenSubKey(
                         @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
                the_Obj = the_Reg.GetValue("");
                the_rar = the_Obj.ToString();
                the_Reg.Close();
                //the_rar = the_rar.Substring(1, the_rar.Length - 7);

                if (Directory.Exists(fileToUnZip) == false)
                {
                    Directory.CreateDirectory(fileToUnZip);
                }
                the_Info = "x " + Path.GetFileName(fileFromUnZip) + " " + fileToUnZip + " -y";

                ProcessStartInfo the_StartInfo = new ProcessStartInfo();
                the_StartInfo.FileName = the_rar;
                the_StartInfo.Arguments = the_Info;
                the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                the_StartInfo.WorkingDirectory = Path.GetDirectoryName(fileFromUnZip);//获取压缩包路径

                Process the_Process = new Process();
                the_Process.StartInfo = the_StartInfo;
                the_Process.StartInfo.UseShellExecute = false;
                the_Process.Start();
                the_Process.WaitForExit();
                the_Process.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //return unRarPatch;
        }

        #endregion 解压文件 .rar文件

        #region 修改上传成功的文件夹名称

        public static void ChangeFileName(string oldFileName)
        {
            string newFileName = oldFileName + "_完成";
            if (System.IO.Directory.Exists(oldFileName))
            {
                System.IO.DirectoryInfo folder = new System.IO.DirectoryInfo(oldFileName);
                folder.MoveTo(newFileName);
            }
        }

        #endregion 修改上传成功的文件夹名称

        #region 解压文件 .zip文件

        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">指定解压目标目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }

            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }

            ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry = null;

            string fileName;

            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(FileToUpZip)))
            {
                string extractKey = ConfigurationManager.AppSettings["ExtractKey"];
                if (!string.IsNullOrEmpty(extractKey))
                {
                    s.Password = extractKey;
                }

                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        ///判断文件路径是否是文件夹如果是文件夹就直接跳过不处理      

                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            //Directory.CreateDirectory(fileName);
                            continue;
                        }

                        // 根据文件目录创建文件所在的根目录路径
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }

                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while ((size = s.Read(data, 0, data.Length)) > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                        }
                    }
                }
            }
        }

        #endregion 解压文件 .zip文件

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>   
        /// <param name="fileToUnZip">待解压的文件</param>   
        /// <param name="zipedFolder">指定解压目标目录</param>   
        /// <param name="password">密码</param>   
        /// <returns>解压结果</returns>   
        public static bool UnZipNew(string fileToUnZip, string zipedFolder, string password)
        {
            bool result = true;

            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            string fileName;

            if (!File.Exists(fileToUnZip))
                return false;

            if (!Directory.Exists(zipedFolder))
                Directory.CreateDirectory(zipedFolder);

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;

                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   
                        if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                        }
                        using (System.IO.FileStream fs = File.Create(fileName))
                        {
                            int size = 2048;
                            byte[] data = new byte[size];
                            while (true)
                            {
                                size = zipStream.Read(data, 0, data.Length);
                                if (size > 0)
                                    fs.Write(data, 0, size);
                                else
                                    break;
                            }
                            fs.Flush();
                            fs.Close();
                            fs.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
                //result = false;
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }


        public static bool IsZip(string file) {
            try
            {
                ZipFile zip = new ZipFile(file);
                zip.Password = null;
                zip.Close();
                return true;
            }
            catch {
                return false;
            }
        }
    }
}

压缩文件test

public void Create_ZIP()
        {
            try
            {
                    //文件压缩
                    string zipName = "xxx.zip";
                    string directoryPath = "路径";
                    string zipPath = Path.Combine(directoryPath, zipName);
                    ZipHelper.CreateZip(excelPath, zipPath);
                    FileStream zipStream = new FileStream(zipPath, FileMode.Open);
                    memoryStream = new MemoryStream();
                    memoryStream.SetLength(zipStream.Length);
                    zipStream.Read(memoryStream.GetBuffer(), 0, (int)zipStream.Length);
                    memoryStream.Flush();
                    zipStream.Close();
            }
            catch (Exception ex)
            {
                Common.LogAPI.Debug(ex);
                //return new HttpResponseMessage(HttpStatusCode.NoContent);
                Response.StatusCode = (int)HttpStatusCode.NoContent;
            }
        }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值