C# ICSharpCode.SharpZipLib.dll文件压缩和解压功能类整理,上传文件或下载文件很常用

工作中我们很多时候需要进行对文件进行压缩,比较通用的压缩的dll就是ICSharpCode.SharpZipLib.dll,废话不多了,网上也有很多的资料,我将其最常用的两个函数整理了一下,提供了一个通用的类,这样在工作中可以快速的完成压缩和解压缩的动作哦

官网下载地址:  http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

1. 在项目中添加对ICSharpCode.SharpZipLib.dll的引用;

2. 在需要使用到ICSharpCode.SharpZipLib中定义的类的编码界面中将其导入(Imports)

 using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO; namespace ZTO.WayBill.Utilities
{
/// <summary>
/// 压缩类
/// http://www.cnblogs.com/kissdodog/p/3525295.html /// </summary>
public class ZipHelper
{
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="source">源目录</param>
/// <param name="s">ZipOutputStream对象</param>
public static void Compress(string source, ZipOutputStream s)
{
string[] filenames = Directory.GetFileSystemEntries(source);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
// 递归压缩子文件夹
Compress(file, s);
}
else
{
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[ * ];
// 此处去掉盘符,如D:\123\1.txt 去掉D:
ZipEntry entry = new ZipEntry(file.Replace(Path.GetPathRoot(file), ""));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
}
}
} /// <summary>
/// 解压缩
/// </summary>
/// <param name="sourceFile">压缩包完整路径地址</param>
/// <param name="targetPath">解压路径是哪里</param>
/// <returns></returns>
public static bool Decompress(string sourceFile, string targetPath)
{
if (!File.Exists(sourceFile))
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
}
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
using (var s = new ZipInputStream(File.OpenRead(sourceFile)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{
continue;
}
string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
if (!Directory.Exists(directorName))
{
Directory.CreateDirectory(directorName);
}
if (!String.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = ;
byte[] data = new byte[size];
while (size > )
{
streamWriter.Write(data, , size);
size = s.Read(data, , data.Length);
}
}
}
}
}
return true;
}
}
}
上一篇:Python网络爬虫第一弹《Python网络爬虫相关基础概念》


下一篇:C# ZipHelper C#公共类 -- ICSharpCode.SharpZipLib.dll实现压缩和解压