SharpZipLib官方介绍
SharpZipLib(#ziplib,以前称为NZipLib)是一个完全用C#编写的用于Zip、GZip、BZip2和Tar的压缩库,适用于.NET。它被实现为一个程序集(可安装到GAC中),因此可以轻松地集成到其他项目中(任何.NET语言)。
使用NuGet 获取并安装
添加引用
using ICSharpCode.SharpZipLib.Zip;
代码示例
public class ZipHelper
{
public void UnZip(string zipFilePath,string unZipDir)
{
if (zipFilePath == string.Empty)
{
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath),Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("/"))
unZipDir += "/";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (directoryName != null && !directoryName.EndsWith("/"))
{
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
int size;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data,data.Length);
if (size > 0)
{
streamWriter.Write(data,size);
}
else
{
break;
}
}
}
}
}
}
}
public void UnZip(byte[] zipFileData,string unZipDir)
{
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
string filePath = string.Empty;
try
{
using (var s = new ZipInputStream(new MemoryStream(zipFileData)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (string.IsNullOrEmpty(directoryName))
{
filePath = Path.Combine(unZipDir,fileName);
}
else
{
var dir = Path.Combine(unZipDir,directoryName);
Directory.CreateDirectory(dir);
if (!string.IsNullOrEmpty(fileName))
{
filePath = Path.Combine(dir,fileName);
}
}
if (filePath != String.Empty)
{
try
{
using (FileStream streamWriter = File.Create(filePath))
{
int size;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data,data.Length);
if (size > 0)
{
streamWriter.Write(data,size);
}
else
{
break;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(filePath);
throw;
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(filePath);
Console.WriteLine(ex.StackTrace);
}
}
}
未完待续...
原文地址:https://blog.csdn.net/rjcql/article/details/134236352
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。