110,536
社区成员
发帖
与我相关
我的任务
分享
using ICSharpCode.SharpZipLib.Zip;
public class ZipHelper
{
public static void Zip(string zipFilePath, string passWord = null, params string[] files)
{
using (var fStream = File.Create(zipFilePath))
{
using (var zoStream = new ZipOutputStream(fStream))
{
if (!string.IsNullOrWhiteSpace(passWord))
{
zoStream.Password = passWord;
}
var buffer = new byte[4096];
foreach (var file in files)
{
var entry = new ZipEntry(Path.GetFileName(file));
zoStream.PutNextEntry(entry);
using (var fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zoStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
zoStream.Finish();
}
}
}
public static IList<string> UnZip(string zipFilePath, string unZipDirectory, string passWord = null)
{
IList<string> list = new List<string>();
using (var ziStream = new ZipInputStream(File.OpenRead(zipFilePath)))
{
if (!string.IsNullOrWhiteSpace(passWord))
{
ziStream.Password = passWord;
}
ZipEntry theEntry;
while ((theEntry = ziStream.GetNextEntry()) != null)
{
if (!Directory.Exists(unZipDirectory))
{
Directory.CreateDirectory(unZipDirectory);
}
string path = Path.Combine(unZipDirectory, theEntry.Name);
using (var streamWriter = File.Create(path))
{
list.Add(path);
var data = new byte[2048];
while (true)
{
var size = ziStream.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
return list;
}
}