C# zip压缩文件的功能


using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

namespace BuildAssetBundle
{

    public class ZipUtility
    {
        /// <summary>
        /// 所有文件缓存
        /// </summary>
        List<string> files = new List<string>();

        /// <summary>
        /// 所有空目录缓存
        /// </summary>
        List<string> paths = new List<string>();

        /// <summary>
        /// 压缩单个文件
        /// </summary>
        /// <param name="fileToZip">要压缩的文件</param>
        /// <param name="zipedFile">压缩后的文件全名</param>
        /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
        /// <param name="blockSize">分块大小</param>
        public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
        {
            if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错
            {
                throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
            }

            FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
            FileStream zipFile = File.Create(zipedFile);
            ZipOutputStream zipStream = new ZipOutputStream(zipFile);
            ZipEntry zipEntry = new ZipEntry(fileToZip);
            zipStream.PutNextEntry(zipEntry);
            zipStream.SetLevel(compressionLevel);
            byte[] buffer = new byte[blockSize];
            int size = streamToZip.Read(buffer, 0, buffer.Length);
            zipStream.Write(buffer, 0, size);

            try
            {
                while (size < streamToZip.Length)
                {
                    int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                    zipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (Exception ex)
            {
                GC.Collect();
                throw ex;
            }

            zipStream.Finish();
            zipStream.Close();
            streamToZip.Close();
            GC.Collect();
        }

        /// <summary>
        /// 压缩目录(包括子目录及所有文件)
        /// </summary>
        /// <param name="rootPath">要压缩的根目录</param>
        /// <param name="destinationPath">保存路径</param>
        /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>
        public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)
        {
            GetAllDirectories(rootPath);

            /* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾
            { 

            rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\" 

            }
            */
            //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
            string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。
            Crc32 crc = new Crc32();
            ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));
            outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression
            foreach (string file in files)
            {
                FileStream fileStream = File.OpenRead(file);//打开压缩文件
                byte[] buffer = new byte[fileStream.Length];
                fileStream.Read(buffer, 0, buffer.Length);
                ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));
                entry.DateTime = DateTime.Now;

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

            this.files.Clear();

            foreach (string emptyPath in paths)
            {
                ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");
                outPutStream.PutNextEntry(entry);
            }

            this.paths.Clear();
            outPutStream.Finish();
            outPutStream.Close();
            GC.Collect();
        }

        /// <summary>
        /// 取得目录下所有文件及文件夹,分别存入files及paths
        /// </summary>
        /// <param name="rootPath">根目录</param>
        private void GetAllDirectories(string rootPath)
        {
            string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录
            foreach (string path in subPaths)
            {
                GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List
            }
            string[] files = Directory.GetFiles(rootPath);
            foreach (string file in files)
            {
                this.files.Add(file);//将当前目录中的所有文件全名存入文件List
            }
            if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录
            {
                this.paths.Add(rootPath);//记录空目录
            }
        }

        /// <summary>
        /// 解压缩文件(压缩文件中含有子目录)
        /// </summary>
        /// <param name="zipfilepath">待解压缩的文件路径</param>
        /// <param name="unzippath">解压缩到指定目录</param>
        /// <returns>解压后的文件列表</returns>
        public List<string> UnZip(string zipfilepath, string unzippath)
        {
            //解压出来的文件列表
            List<string> unzipFiles = new List<string>();

            //检查输出目录是否以“\\”结尾
            if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false)
            {
                unzippath += "\\";
            }

            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(unzippath);
                string fileName = Path.GetFileName(theEntry.Name);

                //生成解压目录【用户解压到硬盘根目录时,不需要创建】
                if (!string.IsNullOrEmpty(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (fileName != String.Empty)
                {
                    //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
                    if (theEntry.CompressedSize == 0)
                        continue;
                    //解压文件到指定的目录
                    directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
                    //建立下面的目录和子目录
                    Directory.CreateDirectory(directoryName);

                    //记录导出的文件
                    unzipFiles.Add(unzippath + theEntry.Name);

                    FileStream streamWriter = File.Create(unzippath + theEntry.Name);

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            s.Close();
            GC.Collect();
            return unzipFiles;
        }

        public string GetZipFileExtention(string fileFullName)
        {
            int index = fileFullName.LastIndexOf(".");
            if (index <= 0)
            {
                throw new Exception("The source package file is not a compress file");
            }

            //extension string
            string ext = fileFullName.Substring(index);

            if (ext == ".rar" || ext == ".zip")
            {
                return ext;
            }
            else
            {
                throw new Exception("The source package file is not a compress file");
            }
        }
    }
}

  

       static string ZipResSourcePath
        {
            get
            {
                foreach (string arg in System.Environment.GetCommandLineArgs())
                {
                    UnityEngine.Debug.Log("ZipResSourcePath:" + arg);
                    if (arg.StartsWith("project"))
                    {
                        return arg.Split(‘-‘)[1];
                    }
                }
                return "";
            }
        }
        static string ZipResDesPath
        {
            get
            {
                foreach (string arg in System.Environment.GetCommandLineArgs())
                {
                    UnityEngine.Debug.Log("ZipResDesPath:" + arg);
                    if (arg.StartsWith("project"))
                    {
                        return arg.Split(‘-‘)[2];
                    }
                }
                return "";
            }
        }

        public static void MultiFilesCompress()
        {
            ZipUtility zip = new ZipUtility();
            DateTime d = DateTime.Now;
            string zipName = @ZipResDesPath + d.ToString("yyyy_MM_dd_HH_mm_ss") + ".zip";
            zip.ZipFileFromDirectory(@ZipResSourcePath, zipName, 4);

            UnityEngine.Debug.LogError("ZipTest Complete:");
        }

  

原文地址:https://www.cnblogs.com/sun-shadow/p/9205510.html

时间: 2024-07-31 08:34:12

C# zip压缩文件的功能的相关文章

dedecms中提取的zip压缩文件操作类zip.class.php

从织梦DeDeCMS中提取的zip压缩文件操作类,包含zip文件压缩.解压缩.添加文件到压缩包中等多个实用的函数,注释详细方便使用. 下载:dedecms中提取的zip压缩文件操作类zip.class.php 包含的函数和简单的使用方法: 1.函数get_List($zip_name) ,函数作用:获取zip文件中的文件列表.函数参数 $zip_name  zip文件名.返回值 文件列表数组. 2.函数Add($files,$compact),函数作用:增加文件到压缩文件.函数参数 $files

php实现ZIP压缩文件解压缩

测试使用了两个办法都可以实现: 第一个:需要开启配置php_aip.dll 1 <?php 2 //需开启配置 php_zip.dll 3 //phpinfo(); 4 header("Content-type:text/html;charset=utf-8"); 5 6 function get_zip_originalsize($filename, $path) { 7 //先判断待解压的文件是否存在 8 if(!file_exists($filename)){ 9 die(

ASP.NET打包生成zip压缩文件

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using Microsoft.Win32; using

Java ZIP压缩文件使用总结

做Java Web开发,有时候遇到将多个文件或者文件夹压缩成一个.zip文件,供前端下载.Java的JDK中提供一个java.util.zip的接口,供大家使用.如下图: 图上就是Java 的JDK提供的接口,但是压缩文件或者文件夹的时候,怎么使用上面的接口呢?下面我给出几个相关的接口,这些接口是下面压缩文件或者文件夹过程中使用到的. java.util.zip.ZipEntry; java.util.zip.ZipOutputStream; 下面的压缩过程主要是通过这两个接口压缩文件或者文件夹

Java—将文件打包为zip压缩文件

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipE

最新Zip压缩文件漏洞,黑客可以触发目录遍历攻击

近日,国内某安全公司研究人员透露了一个关键漏洞的详细信息,该漏洞影响了许多生态系统中的数千个项目,黑客可以利用这些漏洞在目标系统上实现代码执行. 黑客是如何通过Zip压缩文件入侵攻击?被称为"ZipSlip"的问题是一个任意的文件覆盖漏洞,在从档案文件中提取文件时触发目录遍历攻击,并影响包括tar,jar,war,cpio,apk,rar和7z在内的大量压缩文件. 用Google,Oracle,IBM,Apache,亚马逊,Spring/Pivotal,Linkedin,Twitter

使用PHP处理zip压缩文件之ZipArchive

PHP5.2以后,强化了对压缩文件的处理,不仅对zip算法,还包括rar算法.gzip算法等都有了相应的支持. 今天,我来和大家分享一下用PHP处理zip文件.我们用到的是ZipArchive类,如果你安装了PHP5.2以上,无需做任何配置即可开始使用该类. 创建压缩文件: <?php //实例化类 $zip = new ZipArchive(); //需要打开的zip文件,文件不存在将会自动创建 $filename = "./test.zip"; if ($zip->op

ZIP压缩文件夹中上个月的文件,并将备份文件拷贝到服务器

遍历文件夹的子文件夹下的所有文件,将上个月的文件集中到一起,然互压缩,并copy到服务器的映射磁盘. static void Main(string[] args) { //原始文件存放的位置 DirectoryInfo theFolder = new DirectoryInfo(@"E:\TestFloder"); //将文件拷贝到该文件夹下 string targetPath = @"D:\test"; DirectoryInfo[] dirInfo = the

Java使用Zip压缩文件或整个目录

1.压缩文件或整个目录 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.zip.ZipEntry