今天给大家推荐一款开源的压缩、解压库SharpZipLib
, SharpZipLib
使用 C# 开发,完全开源,用于处理 ZIP、GZip、Tar 和 BZip2 等文件格式。该类库提供了丰富的文件压缩和解压功能,包括读取、写入、修改、加密等。是一个强大、易用、跨平台的文件压缩和解压工具。
dotnet add package SharpZipLib --version 1.4.2
NuGet\Install-Package SharpZipLib -Version 1.4.2
string fileToZip = "H:\\1.txt";string zipedFile = "H:\\1.zip";if (!File.Exists(fileToZip)){
throw new System.IO.FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");}using (FileStream fs = File.OpenRead(fileToZip)){
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
using (FileStream ZipFile = File.Create(zipedFile))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(5);
ZipStream.Write(buffer, 0, buffer.Length);
ZipStream.Finish();
ZipStream.Close();
}
}}
string strDirectory = "H:\\zipDir"; //解压目录string zipedFile = "H:\\1.zip"; //要解压的zip文件string password = "123456"; //解压密码bool overWrite = true; //是否覆盖已有文件if (strDirectory == "")
strDirectory = Directory.GetCurrentDirectory();if (!strDirectory.EndsWith("\\"))
strDirectory = strDirectory + "\\";using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile))){
if (password != null)
{
s.Password = password;
}
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = "";
string pathToZip = "";
pathToZip = theEntry.Name;
if (pathToZip != "")
directoryName = Path.GetDirectoryName(pathToZip) + "\\";
string fileName = Path.GetFileName(pathToZip);
Directory.CreateDirectory(strDirectory + directoryName);
if (fileName != "")
{
if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
{
using (FileStream streamWriter = File.Create(strDirectory + directoryName + 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();}