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
}
}

C#压缩文件,C#压缩文件夹,C#获取文件的更多相关文章

  1. Java IO,io,文件操作,删除文件,删除文件夹,获取文件父级目录

    Java IO,io,文件操作,删除文件,删除文件夹,获取文件父级目录 这里先简单的贴下常用的方法: File.separator //当前系统文件分隔符 File.pathSeparator // ...

  2. Java中递归的优缺点,Java写一个递归遍历目录下面的所有文件包括子文件夹里边的文件。

    题目: 遍历出aaa文件夹下的文件 首先分析思路: 1.首先判断这个文件夹是否为文件,通过isFile()函数可以判断是否为文件. 2.然后通过isDirectory判断是否为目录. 3.如果是目录就 ...

  3. php遍历一个文件下的所有文件和子文件夹下的文件

    function AllFile($dir){ if($dh = opendir($dir)){ while (($file = readdir($dh)) !== false){ if($file ...

  4. MFC下打开选择文件夹并获取文件夹的绝对路径

    http://blog.csdn.net/w18758879921/article/details/51613382 http://www.cnblogs.com/greatverve/archive ...

  5. C# 递归查找文件夹下所有文件和子文件夹的所有文件

    方法实现 public class DirectoryAllFiles { static List<FileInformation> FileList = new List<File ...

  6. c#下载共享文件夹下的文件并记录错误日志

    public void Run() { //获取目标文件列表 string _ErrorMessage = ""; string _ErrorMessageFile = " ...

  7. sharepoint REST API 获取文件夹及文件

    使用REST操作文件夹: 获取文件夹 url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Shared Documents')/f ...

  8. 背水一战 Windows 10 (85) - 文件系统: 获取文件夹和文件, 分组文件夹, 排序过滤文件夹和文件, 搜索文件

    [源码下载] 背水一战 Windows 10 (85) - 文件系统: 获取文件夹和文件, 分组文件夹, 排序过滤文件夹和文件, 搜索文件 作者:webabcd 介绍背水一战 Windows 10 之 ...

  9. 使用idea写ssm的时候提示源文件夹中的文件找不到

    <context:property-placeholder location="classpath:db.properties"/>这一行idea提示找不到db.pro ...

随机推荐

  1. Chrome如何访问外网

    分享一下谷歌Chrome浏览器如何访问外网(FQ) 1.请确保你已经安装谷歌浏览器,同时能上网 2. 访问外网需要下载谷歌浏览器插件,网盘链接 https://pan.baidu.com/s/1R-b ...

  2. 简述at和crontab命令

    at 在指定时间执行相关命令 用法:at [option] TIME 常用选项: -l:查询等待运行作业的队列 -d:删除作业,加作业号 -q QUEVE: -c :查看具体作业任务: -f /pat ...

  3. auto-encoder小记

    1.使用auto-encoder生成手写数字 2.中间code层使用二维向量,使用L2norm处理中间层数据 3.从[-1,1]的矩形框中等间隔选取100个坐标点 作为code值 最终生成图像 后期应 ...

  4. loj#2720. 「NOI2018」你的名字

    链接大合集: loj uoj luogu bzoj 单纯地纪念一下写的第一份5K代码.../躺尸 因为ZJOI都不会所以只好写NOI的题了... 总之字符串题肯定一上来就拼个大字符串跑后缀数组啦! ( ...

  5. 20. Web proxies (网页代理 4个)

    用于评估Web应用程序漏洞的基于Java的Web代理. 它支持在运行时编辑/查看HTTP / HTTPS消息,以更改Cookie和表单字段等项. 它包括网络流量记录器,网络蜘蛛,哈希计算器和用于测试常 ...

  6. idea调试代码跟踪到tomcat代码里面

    在POM.xml文件里面加上如下代码即可: <dependency> <groupId>org.apache.tomcat</groupId> <artifa ...

  7. 【转】Linux环境进程间通信(五) 共享内存(上)

    转自:https://www.ibm.com/developerworks/cn/linux/l-ipc/part5/index1.html 采用共享内存通信的一个显而易见的好处是效率高,因为进程可以 ...

  8. Tornado异步非阻塞的使用以及原理

    Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快.得利于其 非阻塞的方式和对 epoll 的运用,Tornado ...

  9. opcache 参数说明 --转自https://www.cnblogs.com/tudou1223/p/5362785.html

    PHP的opcode缓存又出了新成员(说新不新,也有一段日子了),那就是opcache.新浪微博等都在使用,惠新宸老师强力推荐.本人最近根据官网地址(http://www.php.net/manual ...

  10. Windows下安装Spark环境

    根据博客总结 https://blog.csdn.net/nxw_tsp/article/details/78281533 需要的安装软件可以在网盘下载: 链接:https://pan.baidu.c ...