C#使用SharpZipLib类库压缩、解压缩单个文件,废话不说了,直接看代码吧,
类库下载地址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
/// <summary>
/// 使用SharpZipLib压缩Zip文件
/// </summary>
/// <param name="srcFile">源文件</param>
/// <param name="dstFile">压缩后的Zip文件</param>
/// <param name="bufferSize">缓冲大小</param>
public static void Zip(string srcFile, string dstFile, int bufferSize)
{
using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
{
using (FileStream fileStreamOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write))
{
using (ZipOutputStream zipOutStream = new ZipOutputStream(fileStreamOut))
{
byte[] buffer = new byte[bufferSize];
ZipEntry entry = new ZipEntry(Path.GetFileName(srcFile));
zipOutStream.PutNextEntry(entry);
int size;
do
{
size = fileStreamIn.Read(buffer, 0, buffer.Length);
zipOutStream.Write(buffer, 0, size);
} while (size > 0);
zipOutStream.Flush();
}
}
}
}
/// <summary>
/// 使用SharpZipLib解压缩Zip文件
/// </summary>
/// <param name="srcFile">Zip源文件</param>
/// <param name="dstFile">解压出来的文件</param>
/// <param name="bufferSize">缓冲大小</param>
public static void UnZip(string srcFile, string dstFile, int bufferSize)
{
using (FileStream fileStreamIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read))
{
using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn))
{
ZipEntry entry = zipInStream.GetNextEntry();
using (FileStream fileStreamOut = new FileStream(dstFile + @"\" + entry.Name, FileMode.Create, FileAccess.Write))
{
int size;
byte[] buffer = new byte[bufferSize];
do
{
size = zipInStream.Read(buffer, 0, buffer.Length);
fileStreamOut.Write(buffer, 0, size);
} while (size > 0);
fileStreamOut.Flush();
}
}
}
}
/// <summary>
/// 测试Zip文件是否完整
/// </summary>
/// <param name="srcFile">Zip源文件</param>
/// <returns></returns>
public static bool Test(string srcFile)
{
bool flag = false;
using (ZipFile zf = new ZipFile(srcFile))
{
flag = zf.TestArchive(true);
}
return flag;
}