使用SharpZIpLib写的压缩解压操作类

使用SharpZIpLib写的压缩解压操作类,已测试。

 public class ZipHelper
{
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="directory"></param>
/// <param name="targetPath"></param>
public static void Zip(string directory, string targetPath)
{
using (var stream = new ZipOutputStream(File.OpenWrite(targetPath)))
{
Zip(directory, stream);
}
} private static void Zip(string directory, ZipOutputStream stream, string entryName = "")
{
//压缩文件
var files = Directory.GetFiles(directory);
var buffer = new byte[];
foreach (string file in files)
{
var entry = new ZipEntry(entryName + Path.GetFileName(file));
entry.DateTime = DateTime.Now;
stream.PutNextEntry(entry); using (var fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, , buffer.Length);
stream.Write(buffer, , sourceBytes);
} while (sourceBytes > );
}
} //压缩子目录
var subDirectories = Directory.GetDirectories(directory);
foreach (var subDirectory in subDirectories)
{
var subEntryName = Path.GetFileName(subDirectory) + "/";
var entry = new ZipEntry(subEntryName);
entry.DateTime = DateTime.Now;
stream.PutNextEntry(entry);
stream.Flush(); Zip(subDirectory, stream, subEntryName);
}
} /// <summary>
/// 解压zip文件
/// </summary>
/// <param name="zipfilePath"></param>
/// <param name="targetDirectory"></param>
public static void Unzip(string zipfilePath, string targetDirectory)
{
if (!File.Exists(zipfilePath))
return; if(!Directory.Exists(targetDirectory))
Directory.CreateDirectory(targetDirectory); using (var stream = new ZipInputStream(File.OpenRead(zipfilePath)))
{
ZipEntry ent = null;
while ((ent = stream.GetNextEntry()) != null)
{
if (string.IsNullOrEmpty(ent.Name))
continue; var path = Path.Combine(targetDirectory, ent.Name);
path = path.Replace('/', '\\'); //创建目录
if (path.EndsWith("\\"))
{
Directory.CreateDirectory(path);
continue;
} //创建文件
using (var fs = File.Create(path))
{
var buffer = new byte[];
var lengthRead = ;
while ((lengthRead = stream.Read(buffer, , buffer.Length)) > )
fs.Write(buffer, , lengthRead);
} }
}
} }
上一篇:plsql 简单介绍


下一篇:将windows目录共享到linux