using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Shared; namespace Helpers
{
public static class ZipFileHelper {
#region Methods /// <summary>
/// 创建 zip 存档,该存档包含指定目录的文件和目录。
/// </summary>
/// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="compressionLevel"></param>
/// <param name="includeBaseDirectory">压缩包中是否包含父目录</param>
public static bool CreatZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName,
CompressionLevel compressionLevel = CompressionLevel.NoCompression,
bool includeBaseDirectory = true)
{
try
{
if (Directory.Exists(sourceDirectoryName)) //目录
if (!File.Exists(destinationArchiveFileName))
{
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
compressionLevel, includeBaseDirectory);
}
else
{
var toZipFileDictionaryList = GetAllDirList(sourceDirectoryName, includeBaseDirectory); using (
var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
)
{
foreach (var toZipFileKey in toZipFileDictionaryList.Keys)
if (toZipFileKey != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(toZipFileKey);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(toZipFileKey, toZipFileDictionaryList[toZipFileKey],
compressionLevel);
}
}
}
else if (File.Exists(sourceDirectoryName))
if (!File.Exists(destinationArchiveFileName))
ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
compressionLevel, false);
else
using (
var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
)
{
if (sourceDirectoryName != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(sourceDirectoryName);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(sourceDirectoryName, toZipedFileName, compressionLevel);
}
}
else
return false;
return true;
}
catch (Exception exception)
{
LogHelper.LogError("Error! ", exception);
MessageBox.Show(exception.StackTrace, exception.Source);
return false;
}
} /// <summary>
/// 创建 zip 存档,该存档包含指定目录的文件和目录。
/// </summary>
/// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
/// <param name="compressionLevel"></param>
public static bool CreatZipFileFromDictionary(Dictionary<string, string> sourceDirectoryName,
string destinationArchiveFileName,
CompressionLevel compressionLevel = CompressionLevel.NoCompression)
{
try
{
using (FileStream zipToOpen = new FileStream(destinationArchiveFileName, FileMode.OpenOrCreate))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
foreach (var toZipFileKey in sourceDirectoryName.Keys)
if (toZipFileKey != destinationArchiveFileName)
{
var toZipedFileName = Path.GetFileName(toZipFileKey);
var toDelArchives = new List<ZipArchiveEntry>();
foreach (var zipArchiveEntry in archive.Entries)
if (toZipedFileName != null &&
(zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
toDelArchives.Add(zipArchiveEntry);
foreach (var zipArchiveEntry in toDelArchives)
zipArchiveEntry.Delete();
archive.CreateEntryFromFile(toZipFileKey, sourceDirectoryName[toZipFileKey],
compressionLevel);
}
}
}
return true;
}
catch (Exception exception)
{
LogHelper.LogError("Error! ", exception);
MessageBox.Show(exception.StackTrace, exception.Source);
return false;
}
} /// <summary>
/// 递归删除文件夹目录及文件
/// </summary>
/// <param name="baseDirectory"></param>
/// <returns></returns>
public static bool DeleteFolder(string baseDirectory)
{
var successed = true;
try
{
if (Directory.Exists(baseDirectory)) //如果存在这个文件夹删除之
{
foreach (var directory in Directory.GetFileSystemEntries(baseDirectory))
if (File.Exists(directory))
File.Delete(directory); //直接删除其中的文件
else
successed = DeleteFolder(directory); //递归删除子文件夹
Directory.Delete(baseDirectory); //删除已空文件夹
}
}
catch (Exception exception)
{
LogHelper.LogError("Error! ", exception);
successed = false;
}
return successed;
} /// <summary>
/// 调用bat删除目录,以防止系统底层的异步删除机制
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
public static bool DeleteDirectoryWithCmd(string dirPath)
{
var process = new Process(); //string path = ...;//bat路径
var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C rd /S /Q \"" + dirPath + "\"")
{
UseShellExecute = false,
RedirectStandardOutput = true
}; //第二个参数为传入的参数,string类型以空格分隔各个参数
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
if (string.IsNullOrWhiteSpace(output))
return true;
return false;
} /// <summary>
/// 调用bat删除文件,以防止系统底层的异步删除机制
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool DelFileWithCmd(string filePath)
{
var process = new Process(); //string path = ...;//bat路径
var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C del /F /S /Q \"" + filePath + "\"")
{
UseShellExecute = false,
RedirectStandardOutput = true
}; //第二个参数为传入的参数,string类型以空格分隔各个参数
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
var output = process.StandardOutput.ReadToEnd();
if (output.Contains(filePath))
return true;
return false;
} /// <summary>
/// 获取目录下所有[文件名,要压缩的相对文件名]字典
/// </summary>
/// <param name="strBaseDir"></param>
/// <param name="includeBaseDirectory"></param>
/// <param name="namePrefix"></param>
/// <returns></returns>
public static Dictionary<string, string> GetAllDirList(string strBaseDir,
bool includeBaseDirectory = false, string namePrefix = "")
{
var resultDictionary = new Dictionary<string, string>();
var directoryInfo = new DirectoryInfo(strBaseDir);
var directories = directoryInfo.GetDirectories();
var fileInfos = directoryInfo.GetFiles();
if (includeBaseDirectory)
namePrefix += directoryInfo.Name + "\\";
foreach (var directory in directories)
resultDictionary =
resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix))
.ToDictionary(k => k.Key, k => k.Value); //.FullName是某个子目录的绝对地址,
foreach (var fileInfo in fileInfos)
if (!resultDictionary.ContainsKey(fileInfo.FullName))
resultDictionary.Add(fileInfo.FullName, namePrefix + fileInfo.Name);
return resultDictionary;
} /// <summary>
/// Zip解压并更新目标文件
/// </summary>
/// <param name="zipFilePath">Zip压缩包路径</param>
/// <param name="unZipDir">解压目标路径</param>
/// <returns></returns>
public static bool UnZip(string zipFilePath, string unZipDir)
{
bool resualt;
try
{
unZipDir = unZipDir.EndsWith(@"\") ? unZipDir : unZipDir + @"\";
var directoryInfo = new DirectoryInfo(unZipDir);
if (!directoryInfo.Exists)
directoryInfo.Create();
var fileInfo = new FileInfo(zipFilePath);
if (!fileInfo.Exists)
return false;
using (
var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite,
FileShare.Read))
{
using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
{
foreach (var zipArchiveEntry in archive.Entries)
if (!zipArchiveEntry.FullName.EndsWith("/"))
{
var entryFilePath = Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"),
@"^\\*", "");
var filePath = directoryInfo + entryFilePath; //设置解压路径
var content = new byte[zipArchiveEntry.Length];
zipArchiveEntry.Open().Read(content, , content.Length); if (File.Exists(filePath) && content.Length == new FileInfo(filePath).Length)
continue; //跳过相同的文件,否则覆盖更新 var sameDirectoryNameFilePath = new DirectoryInfo(filePath);
if (sameDirectoryNameFilePath.Exists)
{
sameDirectoryNameFilePath.Delete(true);
DeleteDirectoryWithCmd(filePath);
/*if (!DeleteDirectoryWithCmd(filePath))
{
Console.WriteLine(filePath + "删除失败");
resualt = false;
break;
}*/
}
var sameFileNameFilePath = new FileInfo(filePath);
if (sameFileNameFilePath.Exists)
{
sameFileNameFilePath.Delete();
DelFileWithCmd(filePath);
/*if (!DelFileWithCmd(filePath))
{
Console.WriteLine(filePath + "删除失败");
resualt = false;
break;
}*/
}
var greatFolder = Directory.GetParent(filePath);
if (!greatFolder.Exists) greatFolder.Create();
File.WriteAllBytes(filePath, content);
}
}
}
resualt = true;
}
catch
(Exception exception)
{
LogHelper.LogError("Error! ", exception);
resualt = false;
}
return resualt;
} #endregion
}
}

[No0000DF]C# ZipFileHelper ZIP类型操作,压缩解压 ZIP 类封装的更多相关文章

  1. (转载)C#压缩解压zip 文件

    转载之: C#压缩解压zip 文件 - 大气象 - 博客园http://www.cnblogs.com/greatverve/archive/2011/12/27/csharp-zip.html C# ...

  2. Java压缩/解压.zip、.tar.gz、.tar.bz2(支持中文)

    本文介绍Java压缩/解压.zip..tar.gz..tar.bz2的方式. 对于zip文件:使用java.util.zip.ZipEntry 和 java.util.zip.ZipFile,通过设置 ...

  3. PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天

    PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...

  4. [iOS 多线程 & 网络 - 2.4] - 大文件下载 (边下边写/暂停恢复下载/压缩解压zip/多线程下载)

    A.需求 边下边写入硬盘 显示下载进度 暂停/恢复 下载 解压文件 多线程下载   B.基本知识 1.小文件下载 如果文件比较小,下载方式会比较多直接用NSData的+ (id)dataWithCon ...

  5. PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载

    文章转载自:https://my.oschina.net/junn/blog/104464 PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PH ...

  6. C#压缩解压zip 文件

    /// <summary> /// Zip 压缩文件 /// </summary> public class Zip { public Zip() { } #region 加压 ...

  7. android压缩解压zip文件

    网上各种方法的收集: 1.上次写了个解压缩功能,但有局限性,比如压缩文件xx.zip 里包括子目录的情况下,执行上次解压缩的功能就不能实现我们想要的效果,于是在网上参考了一下java的解压缩功能.对上 ...

  8. 原生java 压缩解压zip文件

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...

  9. linux 压缩 解压zip 命令

    将当前目录下的所有文件和文件夹全部压缩成test.zip文件,-r表示递归压缩子目录下所有文件zip -r test.zip ./* 打包目录zip test2.zip test2/*解压test.z ...

随机推荐

  1. Python多进程库multiprocessing中进程池Pool类的使用[转]

    from:http://blog.csdn.net/jinping_shi/article/details/52433867 Python多进程库multiprocessing中进程池Pool类的使用 ...

  2. Windows安装Flask Traceback (most recent call last):

    Exception: File "c:\users\appdata\local\programs\python\python36-32\lib\site-packages\pip\compa ...

  3. 3.翻译系列:EF Code-First 示例(EF 6 Code-First系列)

    原文链接:http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx EF 6 Code-Firs ...

  4. input框触发回车事件

    window.event只能在IE下运行,不能在firefox下运行,这是因为firefox的event只能在事件发生的现场使用.   在firefox里直接调用event对象会报undefined. ...

  5. MySQL在线删除多余的binlog文件

    如果你的MySQL搭建了主从同步 , 或者数据库开启了log-bin日志(MySQL默认开启) , 那么随着时间的推移 , 你的数据库data 目录下会产生大量的日志文件 ll /opt/mysql/ ...

  6. 【R作图】lattice包,画多个分布柱形图,hist图纵轴转换为百分比

    一开始用lattice包,感觉在多元数据的可视化方面,确实做得非常好.各种函数,可以实现任何想要实现的展示. barchart(y ~ x) y对x的直方图 bwplot(y ~ x) 盒形图 den ...

  7. python工具 - 从文件名读取特定信息到excel表格

    情景:文件名中包含学号和用户名,其中用户名在前学好在后,学号为2位,如harry33.txt.natasha12.txt. 要求:将多个文件名中的用户名与学号分开并保存到excle中. 代码部分: i ...

  8. [APM] 解读2016之APM国内篇:快速增长的APM市场和技术

    前言 2016年是APM技术和市场快速发展的一年,在这一年里APM市场特别是国内的市场取得了极大的增长,用户对APM价值的认识和接受度也有了很大的提升,国内市场已基本完成了用户教育和市场培养的阶段.与 ...

  9. python 的正则表达式

    在python中,对正则表达式的支持是通过re模块来支持的.使用re的步骤是先把表达式字符串编译成pattern实例,然后在使用pattern去匹配文本获取结果. 其实也有另外一种方式,就是直接使用r ...

  10. AllPay(欧付宝)支付接口集成

    AllPay,http://www.allpay.com.tw/,欧付宝是台湾知名的第三方支付公司,拥有丰富的支付模式(支持和支付宝.财付通),只需要一次对接,各种支付模式均可使用. 接口编写SDK: ...