ZIP文件压缩和解压
最近要做一个文件交互,上传和下载, 都是zip压缩文件,所以研究了下,写了如下的示例
注意引用 ICSharpCode.SharpZipLib.dll 文件
该dll文件可以到官方网站去下载, 我这里提供一个 .Net FrameWork 2.0 版本的 ,点此下载
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip; namespace ConZIPTools
{
class Program
{
public static void Main(string[] args)
{
try
{
// ZipTool.UnZIP(@"F:\SharpZipLib_0860_Bin.zip", @"F:\M\SharpZipLib_0860_Bin\"); ZipTool.CreateZIP(@"F:\M\SharpZipLib_0860_Bin\net-11", @"F:\m.zip");
}
catch (Exception ex)
{ Console.WriteLine(ex.Message);
}
Console.WriteLine("程序执行完毕");
Console.ReadLine();
}
} public class ZipTool
{
/// <summary>
/// zip 压缩文件, 解压
/// </summary>
/// <param name="zipFilePath">zip压缩文件路径, 例如;F:\SharpZipLib_0860_Bin.zip</param>
/// <param name="saveDirectory">压缩文件加压后的路径,例如 F:\M\SharpZipLib_0860_Bin\ ,注意后面要带'\'</param>
public static void UnZIP(string zipFilePath, string saveDirectory)
{
// Perform simple parameter checking.
if (!File.Exists(zipFilePath))
{
Console.WriteLine("指定的文件路径找不到:" + zipFilePath);
return;
}
if (!Directory.Exists(saveDirectory))
{
//解压后存放的 文件夹路径
Directory.CreateDirectory(saveDirectory);
} using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{ ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
Console.WriteLine("解压出来的文件名:" + theEntry.Name); string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name); // create directory
if (directoryName.Length > )
{
//创建目录
string saveDir = saveDirectory + directoryName;
Directory.CreateDirectory(saveDir);
} if (fileName != String.Empty)
{
string saveFilePath = saveDirectory + theEntry.Name;
using (FileStream streamWriter = File.Create(saveFilePath))
{
int size = ;
byte[] data = new byte[];
while (true)
{
size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
}
}
}
} } /// <summary>
/// 创建 zip压缩文件
/// </summary>
/// <param name="fileDirectoryPath">需要压缩的文件夹路径,注意只压缩里面的文件, 不包括该文件夹下的子文件夹</param>
/// <param name="saveZipFile">保存后zip文件路径</param>
public static void CreateZIP(string fileDirectoryPath, string saveZipFile)
{
// Perform some simple parameter checking. More could be done
// like checking the target file name is ok, disk space, and lots
// of other things, but for a demo this covers some obvious traps. if (!Directory.Exists(fileDirectoryPath))
{
Console.WriteLine("Cannot find directory '{0}'", fileDirectoryPath);
return;
} try
{
// Depending on the directory this could be very large and would require more attention
// in a commercial package.
string[] filenames = Directory.GetFiles(fileDirectoryPath); if (filenames.Length<)
{
Console.WriteLine("该路径下的没有文件:" + fileDirectoryPath);
return;
}
// 'using' statements guarantee the stream is closed properly which is a big source
// of problems otherwise. Its exception safe as well which is great.
using (ZipOutputStream s = new ZipOutputStream(File.Create(saveZipFile)))
{
s.SetLevel(); // 0 - store only to 9 - means best compression byte[] buffer = new byte[]; foreach (string file in filenames)
{ // Using GetFileName makes the result compatible with XP
// as the resulting path is not absolute.
var entry = new ZipEntry(Path.GetFileName(file)); // Setup the entry data as required. // Crc and size are handled by the library for seakable streams
// so no need to do them here. // Could also use the last write time or similar for the file.
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file))
{ // Using a fixed size buffer here makes no noticeable difference for output
// but keeps a lid on memory usage.
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
s.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
} // Finish/Close arent needed strictly as the using statement does this automatically // Finish is important to ensure trailing information for a Zip file is appended. Without this
// the created file would be invalid.
s.Finish(); // Close is important to wrap things up and unlock the file.
s.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Exception during processing {0}", ex); // No need to rethrow the exception as for our purposes its handled.
}
}
}
}
ZIP文件压缩和解压的更多相关文章
- python zip文件压缩和解压
压缩 import shutil zipOutputName = "1234" # 输出1234.zip fileType = "zip" # 文件类型zip ...
- Ionic.Zip.dll文件压缩和解压
Ionic.Zip.dll文件压缩和解压 下载地址: http://download.csdn.net/detail/yfz19890410/5578515 1.下载Ionic.Zip.dll组件,添 ...
- linux常用命令:4文件压缩和解压命令
文件压缩和解压命令 压缩命令:gzip.tar[-czf].zip.bzip2 解压缩命令:gunzip.tar[-xzf].unzip.bunzip2 1. 命令名称:gzip 命令英文原意:GNU ...
- .net文件压缩和解压及中文文件夹名称乱码问题
/**************************注释区域内为引用http://www.cnblogs.com/zhaozhan/archive/2012/05/28/2520701.html的博 ...
- .NET中zip的压缩和解压
在.NET可以通过多种方式实现zip的压缩和解压:1.使用System.IO.Packaging:2.使用第三方类库:3.通过 System.IO.Compression 命名空间中新增的ZipArc ...
- c#自带压缩类实现的多文件压缩和解压
用c#自带的System.IO.Compression命名空间下的压缩类实现的多文件压缩和解压功能,缺点是多文件压缩包的解压只能调用自身的解压方法,和现有的压缩软件不兼容.下面的代码没有把多文件的目录 ...
- java 文件压缩和解压(ZipInputStream, ZipOutputStream)
最近在看java se 的IO 部分 , 看到 java 的文件的压缩和解压比较有意思,主要用到了两个IO流-ZipInputStream, ZipOutputStream,不仅可以对文件进行压缩,还 ...
- 黄聪:.NET中zip的压缩和解压——SharpCompress
使用Packaging无法实现通用的zip(使用其他工具压缩)的解压,只支持通过Packaging压缩包zip的解压,而SharpZipLib是基于“GPL”开源方式,风险比较大.在codeplex找 ...
- 文件压缩和解压 FileStream GZipStream
using (FileStream reader=new FileStream (@"c:\1.txt",FileMode.Open,FileAccess.Read)) { usi ...
随机推荐
- 对状压dp的见解
看了好几篇博客,终于对一些简单的状压dp有了点了解.就像HDU1074. 有个博客:https://blog.csdn.net/bentutut/article/details/70147989 感觉 ...
- Jmeter 集成Excel读写接口参数返回值
输入VIN然后获取返回值json 串,拼接非规则json 标题头 以下是返回的json串 { "error": "success", "result& ...
- for别名
name:for(int i =0 ;i< a.length;i++){ System.out.println(i); for(int j =0;j<i;j++){ continue na ...
- Spring Boot中JPA如何实现按日期合计
1. 用queryDsl方法 JPAQueryFactory.select( Projections.fields(OrderCountByDayBean.class, qOrder.amount.s ...
- 使用wget下载oracle jdk1.8
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com% ...
- logback日志简记
%date{HH:mm:ss.SSS} [%thread] %-5level %logger{20}:%line - %msg%n 输出: 09:54:09.657 [main] INFO c.e. ...
- disruptor 问题排查
需求:收到银行异步通知,要在2秒内将结果返回银行,同时还要根据银行返回的交易状态更新数据库订单状态和其他业务. 采用disruptor,其实最好使用独立MQ产品.本次用的是disruptor,遇到了一 ...
- 问题解决Determine IP information for eth0.. no link present check cable
网上方法都没有解决:简单粗暴编辑里还原了默认设置OK了 网上方法1 一般解决办法: 第一步: 到/etc/sysconfig/network-scripts/ifcfg-eth<n>/et ...
- c++ 封装线程库 0
1.互斥锁简介 互斥锁主要用于互斥,互斥是一种竞争关系,用来保护临界资源一次只被一个线程访问. POSIX Pthread提供下面函数用来操作互斥锁. int pthread_mutex_init(p ...
- Android NDK开发 环境配置(一) 之多重CPU的兼容性
今天我学习Android Studio当中的NDK,为什么要学习NDK呢,是因为领导给我提了一个BUG,这个BUG就是Android 多重CPU怎样兼容性,我现在先说一下,Android Studio ...