第一步:首先添加对ICSharpCode.SharpZipLib.dll动态链接库的引用,需要引用的命名空间如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.GZip;
第二步:开始编写对文件或者文件夹的解压与压缩程序
程序一:将文件集合
/// <summary>
/// 将原文件的压缩到指定目录下并命名为指定文件名
/// </summary>
/// <param name="sourceFiles">源文件的存储地址集合</param>
/// <param name="zipFolderPath">压缩文件的输出目录</param>
/// <param name="zipFileName">压缩文件的文件名称</param>
public static void GetZipFromFiles(List<string> sourceFiles, string zipFolderPath, string zipFileName)
{
zipFolderPath = zipFolderPath + @"/" + zipFileName + ".zip";
FileStream ZipFileStream = File.Create(zipFolderPath);
ZipOutputStream ZipOutStream = new ZipOutputStream(ZipFileStream);
sourceFiles.ForEach(e =>
{
FileStream myFileStream = File.OpenRead(e);
byte[] ByteBuffer = new byte[myFileStream.Length];
myFileStream.Read(ByteBuffer, 0, ByteBuffer.Length);
myFileStream.Close();
ZipEntry ZipFileEntry = new ZipEntry(Path.GetFileName(e));
ZipOutStream.PutNextEntry(ZipFileEntry);
ZipOutStream.SetLevel(6);
ZipOutStream.Write(ByteBuffer, 0, ByteBuffer.Length);
});
ZipOutStream.Finish();
ZipOutStream.Close();
}