说明:
引用 using ICSharpCode.SharpZipLib.Zip;
代码如下:
//调用:CreateZipFile("文件路径","压缩路径")
private static void CreateZipFile(string filesPath, string zipFilePath)
{
if (!Directory.Exists(filesPath))
{
MessageBox.Show("找不到 " + filesPath);
return;
}
try
{
string[] filenames = Directory.GetFiles(filesPath);
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(9); // 压缩级别 0-9
//s.Password = "123"; //Zip压缩文件密码
byte[] buffer = new byte[4096]; //缓冲区大小
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//UnZipFile("压缩路径","文件路径")
private static void UnZipFile(string zipFilePath, string unZipFilePath)
{
if (!File.Exists(zipFilePath))
{
MessageBox.Show(zipFilePath + " 不存在!");
return;
}
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
string directoryName = Path.GetDirectoryName(unZipFilePath);
// create directory
if (directoryName.Length > 0)
{
Directory.CreateDirectory(directoryName);
}
while ((theEntry = s.GetNextEntry()) != null)
{
//string fileName = Path.GetFileName(theEntry.Name);
string fileName = Path.Combine(unZipFilePath,theEntry.Name);
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
s.Close();
}
}
附,使用ICSharpCode SharpZipLib进行压缩与解压缩文件或文件夹的代码。
1、解压缩代码
using System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
namespace DRMEncryption
{
/// ;summary;
/// UnZip 类用于解压缩一个 zip 文件。
/// ;/summary;
public class UnZipDir
{
//解压缩以后的文件名和路径,压缩前的路径
public static Boolean UNZipFile(string FileToZip, string ZipedFile)
{
try
{
FastZip fastZip = new FastZip();
fastZip.ExtractZip(FileToZip, ZipedFile, "");
return true;
}
catch {
return false;
}
}
}
}
2、压缩文件的代码
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.gzip;
namespace DRMEncryption
{
public class ZipClass
{
public static Boolean ZipFile(string FileToZip, string ZipedFile)
{
try
{
FastZip fastZip = new FastZip();
bool recurse = true;
//压缩后的文件名,压缩目录 ,是否递归
fastZip.CreateZip(FileToZip, ZipedFile, recurse, "");
return true;
}
catch { return false; }
}
}
}
说明:
那个返回方法是用来另外一个页面判断解压是否成功用的,可以不要;
解压缩:UnZipDir.UNZipFile(文件名, 路径);
压缩:ZipClass.ZipFile(文件名, 路径);
就是这些了,希望有需要的朋友,可以从中受益,呵呵。