安装nuget SharpZipLib 1.4.2
public class ZipHelper
{
/// <summary>
/// 压缩文件/文件夹
/// </summary>
/// <param name="filePath">需要压缩的文件/文件夹路径</param>
/// <param name="zipPath">压缩文件路径(zip后缀)</param>
/// <param name="password">密码</param>
/// <param name="filterExtenList">需要过滤的文件后缀名</param>
public static void CompressionFile(string filePath, string zipPath, string password)
{
try
{
using (ZipFile zip = ZipFile.Create(zipPath))
{
zip.Password = password;
var fileInfo = new FileInfo(filePath);
zip.BeginUpdate();
zip.Add(filePath, fileInfo.Name);
zip.CommitUpdate();
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void DepressionFile(string zipPath, string dir, string password)
{
using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(zipPath)))
{
//每个包含在Zip压缩包中的文件都被看成是ZipEntry对象,并通过ZipInputStream的GetNextEntry方法
//依次遍历所有包含在压缩包中的文件。
ZipEntry ent;
zipStream.Password = password;
while ((ent = zipStream.GetNextEntry()) != null)
{
//theEntry.CanDecompress
if (ent.IsDirectory)
{
continue;
}
if (string.IsNullOrEmpty(ent.Name))
{
continue;
}
string fileName = dir + "\\" + ent.Name.Replace('/', '\\');
var index = ent.Name.LastIndexOf('/');
if (index != -1)
{
string path = dir + ent.Name.Substring(0, index).Replace('/', '\\');
System.IO.Directory.CreateDirectory(path);
}
var bytes = new byte[ent.Size];
zipStream.Read(bytes, 0, bytes.Length);
System.IO.File.WriteAllBytes(fileName, bytes);
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
留待后查,同时方便他人