1.Ionic.zIP 实现文件压缩和解压
2.压缩:
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="zipdirectory">压缩文件目录</param>
/// <param name="zipfileName">压缩文件名称</param>
/// <param name="adddirectoryfile">需要添加到压缩文件的目录 物理路径</param>
/// <param name="addfiles">需要添加到压缩文件的文件 物理路径</param>
/// <returns>是否成功</returns>
/// <example>
/// CompZipFiles(@"E:\zipfile",DateTime.Now.ToString("yyMMddHHmmssff") + ".zip",@"E:\testzip",new string[]{@"E:\crebas.sql"}}
/// CompZipFiles(@"E:\zipfile",DateTime.Now.ToString("yyMMddHHmmssff") + ".zip",@"E:\testzip",null}
/// </example>
public bool CompZipFiles(string zipdirectory, string zipfileName, string adddirectoryfile, string[] addfiles)
{
bool result = false;//是否成功
try
{
if (!Directory.Exists(zipdirectory)) Directory.CreateDirectory(zipdirectory);
using (ZipFile zip = new ZipFile(zipdirectory + "\" + zipfileName, Encoding.Default))
{
zip.Password = "lin.su";//加密压缩
if (!string.IsNullOrEmpty(adddirectoryfile)) zip.AddDirectory(adddirectoryfile);//添加目录到zip中
if (addfiles!=null && addfiles.Length > 0)
{
for (int i = 0; i < addfiles.Length; i++)
{
zip.AddFile(addfiles[i]);//添加文件到zip中
}
}
zip.Save();
result = true;
}
}
catch (Exception)
{
throw;
}
return result;
}
3.解压:
/// <summary>
/// 解压文件
/// </summary>
/// <param name="zipdirectory">zip 文件目录</param>
/// <param name="zipfileName">zip文件名称</param>
/// <param name="dedirectoryfile">解压目标文件目录</param>
/// <param name="defiles">解压的文件名称</param>
/// <param name="isAll">是否全部解压</param>
/// <returns>是否成功</returns>
/// <example>
/// ExtractZipFiles(@"E:\zipfile", "13120210435607.zip", @"E:\testzip2", new string[]{@"E:\crebas.sql"}, false);
/// ExtractZipFiles(@"E:\zipfile", "13120210435607.zip", @"E:\testzip2", null, true);
/// </example>
public bool ExtractZipFiles(string zipdirectory, string zipfileName, string extractdirectoryfile, string[] extractfiles, bool isAll)
{
bool result = false;//是否成功
try
{
if (!Directory.Exists(extractdirectoryfile)) Directory.CreateDirectory(extractdirectoryfile);
using (ZipFile zip = ZipFile.Read(zipdirectory + "\" + zipfileName ))
{
zip.Password = "lin.su";//密码解压
//Extract解压zip文件包的方法
if (isAll)
{
foreach (ZipEntry entry in zip)
{
//Extract解压zip文件包的方法,参数是保存解压后文件的路基
entry.Extract(extractdirectoryfile);
}
}
else
{
if(extractfiles!=null && extractfiles.Length>0){
for (int i = 0; i < extractfiles.Length; i++)
{
zip[extractfiles[i]].Extract(extractdirectoryfile);
}
}
}
result = true;
}
}
catch (Exception)
{
throw;
}
return result;
}
备注:解压出来的文件名如果有中文,则会出现乱码(是程序自动解压会有乱码)如果是手动解压就没有问题,不知道什么原因,估计有要修改源代码,如果谁弄好告诉我了