C# 文件/文件夹压缩解压缩
项目上用到的,随手做个记录,哈哈。
直接上代码:
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
namespace BLL
{
/// <summary>
/// 文件(夹)压缩、解压缩
/// </summary>
public class FileCompression
{
#region 压缩文件
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileNames">要打包的文件列表</param>
/// <param name="GzipFileName">目标文件名</param>
/// <param name="CompressionLevel">压缩品质级别(0~9)</param>
/// <param name="deleteFile">是否删除原文件</param>
public static void CompressFile(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
{
ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
try
{
s.SetLevel(CompressionLevel); //0 - store only to 9 - means best compression
foreach (FileInfo file in fileNames)
{
FileStream fs = null;
try
{
fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
}
catch
{ continue; }
// 方法二,将文件分批读入缓冲区
byte[] data = new byte[];
int size = ;
ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
s.PutNextEntry(entry);
while (true)
{
size = fs.Read(data, , size);
if (size <= ) break;
s.Write(data, , size);
}
fs.Close();
if (deleteFile)
{
file.Delete();
}
}
}
finally
{
s.Finish();
s.Close();
}
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="dirPath">要打包的文件夹</param>
/// <param name="GzipFileName">目标文件名</param>
/// <param name="CompressionLevel">压缩品质级别(0~9)</param>
/// <param name="deleteDir">是否删除原文件夹</param>
public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
{
//压缩文件为空时默认与压缩文件夹同一级目录
if (GzipFileName == string.Empty)
{
GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + );
GzipFileName = dirPath.Substring(, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
}
//if (Path.GetExtension(GzipFileName) != ".zip")
//{
// GzipFileName = GzipFileName + ".zip";
//}
using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
{
zipoutputstream.SetLevel(CompressionLevel);
Crc32 crc = new Crc32();
Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
foreach (KeyValuePair<string, DateTime> item in fileList)
{
FileStream fs = File.OpenRead(item.Key.ToString());
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
entry.DateTime = item.Value;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, , buffer.Length);
}
}
if (deleteDir)
{
Directory.Delete(dirPath, true);
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
private static Dictionary<string, DateTime> GetAllFies(string dir)
{
Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
throw new System.IO.FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
}
GetAllDirFiles(fileDire, FilesList);
GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
return FilesList;
}
/// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
}
/// <summary>
/// 获取一个文件夹下的文件
/// </summary>
/// <param name="dir">目录名称</param>
/// <param name="filesList">文件列表HastTable</param>
private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
#endregion
#region 解压缩文件
/// <summary>
/// 解压缩文件
/// </summary>
/// <param name="GzipFile">压缩包文件名</param>
/// <param name="targetPath">解压缩目标路径</param>
public static void Decompress(string GzipFile, string targetPath)
{
//string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";
string directoryName = targetPath;
if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录
string CurrentDirectory = directoryName;
byte[] data = new byte[];
int size = ;
ZipEntry theEntry = null;
using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
{
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{// 该结点是目录
if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
}
else
{
if (theEntry.Name != String.Empty)
{
// 检查多级目录是否存在
if (theEntry.Name.Contains("//"))
{
string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + );
if (!Directory.Exists(parentDirPath))
{
Directory.CreateDirectory(CurrentDirectory + parentDirPath);
}
} //解压文件到指定的目录
using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
{
while (true)
{
size = s.Read(data, , data.Length);
if (size <= ) break;
streamWriter.Write(data, , size);
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
#endregion
}
}
封装的很彻底,基本不用修改什么,直接拿来用就行了。
找了很久,终于知道怎么把源代码附上了
源代码:https://files.cnblogs.com/files/hahahayang/C%E5%8E%8B%E7%BC%A9%E6%96%87%E4%BB%B6.zip
C# 文件/文件夹压缩解压缩的更多相关文章
- 使用Java API进行tar.gz文件及文件夹压缩解压缩
在java(JDK)中我们可以使用ZipOutputStream去创建zip压缩文件,(参考我之前写的文章 使用java API进行zip递归压缩文件夹以及解压 ),也可以使用GZIPOutputSt ...
- Linux文件的加压缩解压缩tar命令
linux下使用tar命令 解压 语法:tar [主选项+辅选项] 文件或者目录 使用该命令时,主选项是必须要有的,它告诉tar要做什么事情,辅选项是辅助使用的,可以选用.主选项:c 创建新的档案 ...
- 使用VC++压缩解压缩文件夹
前言 项目中要用到一个压缩解压缩的模块, 看了很多文章和源代码, 都不是很称心, 现在把我自己实现的代码和大家分享. 要求: 1.使用Unicode(支持中文). 2.使用源代码.(不使用静态或 ...
- C#压缩、解压缩文件(夹)(rar、zip)
主要是使用Rar.exe压缩解压文件(夹)(*.rar),另外还有使用SevenZipSharp.dll.zLib1.dll.7z.dll压缩解压文件(夹)(*.zip).需要注意的几点如下: 1.注 ...
- C#文件或文件夹压缩和解压方法(通过ICSharpCode.SharpZipLib.dll)
我在网上收集一下文件的压缩和解压的方法,是通过ICSharpCode.SharpZipLib.dll 来实现的 一.介绍的目录 第一步:下载压缩和解压的 ICSharpCode.SharpZipLib ...
- SharpZipLib 文件/文件夹压缩
一.ZipFile ZipFile类用于选择文件或文件夹进行压缩生成压缩包. 常用属性: 属性 说明 Count 文件数目(注意是在ComitUpdat之后才有) Password 压缩包密码 Siz ...
- ubuntu下文件压缩/解压缩命令总结
.gz 解压1:gunzip FileName.gz 解压2:gzip -d FileName.gz 压缩:gzip FileName .tar.gz 解压:tar zxvf FileName.tar ...
- C# 文件/文件夹压缩
一.ZipFile ZipFile类用于选择文件或文件夹进行压缩生成压缩包. 常用属性: 属性 说明 Count 文件数目(注意是在ComitUpdat之后才有) Password 压缩包密码 Siz ...
- 使用 apache ant 轻松实现文件压缩/解压缩(转)
原文地址:http://blog.csdn.net/irvine007/article/details/6779492 maven配置ant包: <dependency> <grou ...
随机推荐
- PostgreSQL 自动输入密码(转)
原文:https://www.cnblogs.com/litmmp/p/5122534.html 在 Shell 命令行中,使用 postgresql-client 连接 PostgreSQL 数据库 ...
- Rosserial实现Windows-ROS交互操作
安装 sudo apt-get install ros-indigo-rosserial-windows sudo apt-get install ros-indigo-rosserial-serve ...
- Python:遍历一个目录下所有的文件及文件夹,然后计算每个文件的字符和line的小程序
编写了一个遍历一个目录下所有的文件及文件夹,然后计算每个文件的字符和line的小程序,先把程序贴出来. #coding=utf-8 ''' Created on 2014年7月14日 @author: ...
- CentOS6.10安装redis5.0
1.以安装redis5.0.0为例 下载安装包:http://redis.io 安装非常简单! [root@centos6 ~]#yum install gcc #需要先安装GCC,如果已安装请忽略 ...
- node(03)--利用 HTTP 模块 URl 模块 PATH 模块 FS 模块创建一个 WEB 服务器
Web 服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,可以向浏览器等 Web 客户端提供文档,也可以放置网站文件,让全世界浏览:可以放置数据文件,让全世界下载.目前最主流的三个 We ...
- CSRF与JSON
之前遇到提交json的请求想要进行csrf攻击都是用的闭合表单的方法,很笨很麻烦, 这次看到了别人的操作记录一下. 这里用到了ajax异步请求(但是这里我有个疑问就是:这里用到了cors跨域,是不是必 ...
- Android -- 贝塞尔曲线公式的推导和简单使用
1,最近看了几个不错的自定义view,发现里面都会涉及到贝塞尔曲线知识,深刻的了解到贝塞尔曲线是进阶自定义view的一座大山,so,今天先和大家来了解了解. 2,贝塞尔曲线作用十分广泛,简单举几个的栗 ...
- caffe-ssd的GPU在make runtest的时候报错:BatchReindexLayerTest/2.TestGradient,where TypeParam=caffe::GPUdevice(<float>)(<double>)
make runtest报错:BatchReindexLayerTest/2.TestGradient,where TypeParam=caffe::GPUdevice<float> Ba ...
- ASP.NET MVC案例教程(二)
ASP.NET MVC案例教程(二) 让第一个页面跑起来 现在,我们来实现公告系统中的第一个页面——首页.它非常简单,只包括所有公告分类的列表,并且每个列表项是一个超链接.其中分类数据是用我们的Moc ...
- m2e-wtp的作用
描述 Maven3下的项目结构,target目录下会有一个m2e-wtp文件夹,删除掉会自动生成,有什么作用呢? wtp解释 WTP:Web Tools Project Maven集成WTP The ...