一、使用ICSharpCode.SharpZipLib.dll;
下载地址
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
二、基于(ICSharpCode.SharpZipLib.dll)的文件压缩方法,类文件
压缩文件
- using System;
- using System.IO;
- using System.Collections;
- using ICSharpCode.SharpZipLib.Checksums;
- using ICSharpCode.SharpZipLib.Zip;
- namespace FileCompress
- {
- /// <summary>
- /// 功能:压缩文件
- /// creator chaodongwang 2009-11-11
- /// </summary>
- public class ZipClass
- {
- /// <summary>
- /// 压缩单个文件
- /// </summary>
- /// <param name="FileToZip">被压缩的文件名称(包含文件路径)</param>
- /// <param name="ZipedFile">压缩后的文件名称(包含文件路径)</param>
- /// <param name="CompressionLevel">压缩率0(无压缩)-9(压缩率最高)</param>
- /// <param name="BlockSize">缓存大小</param>
- public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel)
- {
- //如果文件没有找到,则报错
- if (!System.IO.File.Exists(FileToZip))
- {
- throw new System.IO.FileNotFoundException("文件:" + FileToZip + "没有找到!");
- }
- if (ZipedFile == string.Empty)
- {
- ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";
- }
- if (Path.GetExtension(ZipedFile) != ".zip")
- {
- ZipedFile = ZipedFile + ".zip";
- }
- ////如果指定位置目录不存在,创建该目录
- //string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("/"));
- //if (!Directory.Exists(zipedDir))
- // Directory.CreateDirectory(zipedDir);
- //被压缩文件名称
- string filename = FileToZip.Substring(FileToZip.LastIndexOf('//') + 1);
- System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
- System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
- ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
- ZipEntry ZipEntry = new ZipEntry(filename);
- ZipStream.PutNextEntry(ZipEntry);
- ZipStream.SetLevel(CompressionLevel);
- byte[] buffer = new byte[2048];