using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/*****************************
 * 概要:File
 * 设计者:DuanXuWen
 * 设计时间:20180309
 * 版本:0.1
 * 修改者:
 * 修改时间:
 * ***************************/
namespace Common
{
    public class FileHelper
    {
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipFilePath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string ZipFiles(string dirPath, string password, string zipFilePath)
        {
            if (zipFilePath == string.Empty)
            {
                //压缩文件名为空时使用文件夹名+.zip
                zipFilePath = GetZipFilePath(dirPath);
            }
            try
            {
                string[] filenames = Directory.GetFiles(dirPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9);
                    s.Password = password;
                    byte[] buffer = new byte[4096];
                    foreach (string file in filenames)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
                return zipFilePath;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

/// <summary>
        /// 减压文件夹
        /// </summary>
        /// <param name="zipFilePath">压缩包地址+名称+后缀</param>
        /// <param name="password">密码(注:可为空)</param>
        /// <param name="unZippath">减压后保存的路径(注:可为空,默认同目录)</param>
        /// <returns></returns>
        public string UnZips(string zipFilePath, string password, string unZippath)
        {
            try
            {
                if (unZippath == string.Empty)
                {
                    //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
                    unZippath = GetUnZipFilePath(zipFilePath);
                }
                if (CreatePath(unZippath) && IsExistFilePath(zipFilePath))
                {
                    string directoryName = Path.GetDirectoryName(unZippath);
                    {
                        using (ZipInputStream zipInStream = new ZipInputStream(File.OpenRead(zipFilePath)))
                        {
                            zipInStream.Password = password;
                            ZipEntry entry = zipInStream.GetNextEntry();
                            do
                            {
                                using (FileStream fileStreamOut = File.Create(directoryName + "\\" + entry.Name))
                                {
                                    int size = 2048;
                                    byte[] buffer = new byte[size];
                                    do
                                    {
                                        size = zipInStream.Read(buffer, 0, buffer.Length);
                                        fileStreamOut.Write(buffer, 0, size);
                                    } while (size > 0);
                                    fileStreamOut.Close();
                                    fileStreamOut.Dispose();
                                }
                            } while ((entry = zipInStream.GetNextEntry()) != null);
                            zipInStream.Close();
                            zipInStream.Dispose();
                            return unZippath;
                        }
                    }
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

/// <summary>  
        /// 压缩文件  
        /// </summary>  
        /// <param name="dirFilePath">文件路径+名称+后缀</param>
        /// <param name="password">压缩包设置密码(注:可为空)</param>
        /// <param name="zipFilePath">压缩包路径+名称+后缀(注:可为空,默认同目录)</param>
        public string ZipFile(string dirFilePath, string password, string zipFilePath)
        {
            try
            {
                if (IsExistFilePath(dirFilePath))
                {
                    if (zipFilePath == string.Empty)
                    {
                        zipFilePath = GetZipFilePath(dirFilePath.Replace(Path.GetExtension(dirFilePath), ""));
                    }
                    string filename = Path.GetFileName(dirFilePath);
                    FileStream streamToZip = new FileStream(dirFilePath, FileMode.Open, FileAccess.Read);
                    FileStream zipFile = File.Create(zipFilePath);
                    using (ZipOutputStream zipStream = new ZipOutputStream(zipFile))
                    {
                        ZipEntry zipEntry = new ZipEntry(filename);
                        zipStream.PutNextEntry(zipEntry);
                        zipStream.SetLevel(9);
                        zipStream.Password = password;
                        byte[] buffer = new byte[2048];
                        System.Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
                        zipStream.Write(buffer, 0, size);
                        while (size < streamToZip.Length)
                        {
                            int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, sizeRead);
                            size += sizeRead;
                        }
                        zipStream.Finish();
                        zipStream.Close();
                        streamToZip.Close();
                    }
                    return zipFilePath;
                }
                return "请确认压缩包文件地址与解压后保存地址是否可以访问!";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

/// <summary>
        /// 创建路径
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public bool CreatePath(string path)
        {
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    return true;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

/// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filePath">路劲+名称+后缀</param>
        /// <returns></returns>
        public bool IsExistFilePath(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return false;
            }
            return true;
        }

/// <summary>
        /// 获取默认压缩路径+文件名+后缀【.zip】
        /// </summary>
        /// <param name="path">需要压缩的文件夹路径(注:不包含.后缀)</param>
        /// <returns>与压缩文件同一目录路径</returns>
        public string GetZipFilePath(string path)
        {
            if (path.EndsWith("\\"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            return path + ".zip";
        }

/// <summary>
        ///  获取默认解压路径
        /// </summary>
        /// <param name="path">需要解压的压缩包文件地址</param>
        /// <returns>与解压文件同一目录路径</returns>
        public string GetUnZipFilePath(string path)
        {
            path = path.Replace(Path.GetFileName(path), Path.GetFileNameWithoutExtension(path));
            if (!path.EndsWith("/"))
            {
                path += "/";
            }
            return path;
        }

/// <summary>
        /// 获取路径中所有文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        private Hashtable getAllFies(string path)
        {
            Hashtable FilesList = new Hashtable();
            DirectoryInfo fileDire = new DirectoryInfo(path);
            if (fileDire.Exists)
            {
                this.getAllDirFiles(fileDire, FilesList);
                this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
            }
            this.getAllDirFiles(fileDire, FilesList);
            this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
            return FilesList;
        }

/// <summary>  
        /// 获取一个文件夹下的所有文件夹里的文件  
        /// </summary>  
        /// <param name="dirs"></param>  
        /// <param name="filesList"></param>  
        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
        {
            foreach (DirectoryInfo dir in dirs)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    filesList.Add(file.FullName, file.LastWriteTime);
                }
                this.getAllDirsFiles(dir.GetDirectories(), filesList);
            }
        }

/// <summary>  
        /// 获取一个文件夹下的文件  
        /// </summary>  
        /// <param name="strDirName">目录名称</param>  
        /// <param name="filesList">文件列表HastTable</param>  
        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
        {
            foreach (FileInfo file in dir.GetFiles("*.*"))
            {
                filesList.Add(file.FullName, file.LastWriteTime);
            }
        }  
    }
}

c# FileHelper 对文件压缩解压,压缩包加密相关推荐

  1. Linux 命令之 rar -- 压缩/解压文件

    文章目录 一.命令介绍 二.子命令 三.常用选项 四.命令示例 (一)压缩指定文件或者更新压缩包内指定的文件 (二)压缩指定目录下的内容(不含目录本身) (三)创建自解压文件 (四)按完整路径解压文件 ...

  2. @linux安装及使用(压缩|解压)工具RAR

    文章目录 1.linux的rar工具 2.rar-linux安装包下载 3.rar工具命令使用介绍 4.使用案列 1.linux的rar工具 1>windows使用winrar可以解压后缀为.r ...

  3. Linux中压缩解压工具使用

    1.压缩原理 目前我们使用的计算机系统是使用bytes单位计量的,实际上,计算机中最小的计量单位是bits 1 byte = 8 bits 在这里插入图片描述 一个空格代表一个bit,1byte就是8 ...

  4. tar+opensll 加密压缩解压

    1 压缩解压 压缩 tar -zcvf /path/to/1.tar.gz 1.txt 解压 tar -zxvf /path/to/1.tar.gz /path/to 指令详解: -z:是否同时具有g ...

  5. R语言使用unzip函数解压压缩文件(Extract or List Zip Archives)

    R语言使用unzip函数解压压缩文件(Extract or List Zip Archives) 目录 R语言使用unzip函数解压压缩文件(Extract or List Zip Archives) ...

  6. 通过C#代码 压缩/解压文件

    通过引用一DLL(ICSharpCode.dll)可以实现所述功能... 一.压缩文件 using System; using ICSharpCode.SharpZipLib; using ICSha ...

  7. 测试掌握的Linux解压,轻松掌握Linux压缩/解压文件的方法

    对于在Linux下解压大型的*.zip文件,相信大家一般都会通过使用winrar直接在smb中来进行解压的操作,虽然说最终可能能够解压但有时候会存在解压时间长或者网络原因出错等故障的情况出现.那么有没 ...

  8. 【PC工具】文件压缩解压工具winrar解压缩装机必备软件,winRAR5.70免费无广告

    微信关注 "DLGG创客DIY" 设为"星标",重磅干货,第一时间送达. 今天分享一个常用的压缩解压工具winrar. 为啥要搞这个无广告版呢(废话),总之网上 ...

  9. java 7zip解压_Apache Commons Compress介绍-JAVA压缩解压7z文件

    7zip(下面简称7z)是由Igor Pavlov所开发的一种压缩格式,主要使用的压缩算法是LZMA/LZMA2.7z是一种压缩比非常高的格式,这与其压缩算法LZMA有直接关系,所以很多大文件都是用7 ...

  10. python批量解压文件_python 批量解压压缩文件的实例代码

    下面给大家介绍python 批量解压压缩文件的实例代码,代码如下所述: #/usr/bin/python#coding=utf-8import os,sys import zipfile open_p ...

最新文章

  1. 前端遍历导致查询数据时间过长_OLAP 服务器,空间换时间可行吗?
  2. luogu p3515 Lightning Conductor
  3. Yii的where中的in写法
  4. Qt笔记-Q_UNUSED解决编译器unused paramenter告警
  5. Linux磁盘分区详解(parted)
  6. Linux 性能测试工具 sysbench 的安装与简单使用
  7. 系统迁移到ssd 开启哪些服务器,如何使用分区助手完美迁移系统到SSD固态硬盘...
  8. STC8单片机驱动ADS1256多路AD采集
  9. OSChina 周日乱弹 —— 你今天又穿女装上班了
  10. 《Web前端技术H5+CSS3》笔记--第一章 HTML基础[云图智联]
  11. 【CS231n】斯坦福大学李飞飞视觉识别课程笔记(六):线性分类笔记(上)
  12. 有限元基础及ANSYS应用 - 第9节 - 2 平面应变问题的ANSYS分析
  13. 如果显示直播连接不成功问题
  14. 都在说软件测试真的干不到35岁,那咋办呢...我都36了...
  15. python调用按键精灵插件_【师兄带你学Python-1】你会涮火锅吗?
  16. 做好项目信息管理,是优秀项目经理的必备技能
  17. 在CentOS7上安装Drone搭建CI持续集成环境
  18. K8s——kubernetes集群中ceph集群使用【上】
  19. 【THUWC2019模拟2019.1.18】Counting
  20. 宁德时代、亿纬锂能储能“列阵”

热门文章

  1. Kubernetes 学习笔记(一)--- 基本概念及利用kubeadm部署K8S
  2. 树梅派 raspberrypi 更换清华源
  3. 2022保研,我的心路历程(上科大上海交大华南理工)
  4. debian 7 调整控制台分辨率
  5. BigDecimal实现加减乘除
  6. 利用树莓派组建支持迅雷离线下载的NAS
  7. layer添加元素 openlayer_OpenLayers使用点要素作为标记
  8. 通过任意数量点拟合曲线
  9. php submit执行函数,jQuery.submit() 函数详解
  10. 【建站笔记】:在wordpress博客文章中插入代码段并高亮显示