.net 6 zip 操作 zip密码
安装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);
}
}
}
}
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com