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. 基于CentOS体验万象优图鉴黄服务

    系统要求:CentOS 7.2 64 位操作系统 初始化配置 使用万象优图图片鉴黄 API 接口,我们需要先完成以下步骤: 获取腾讯云账号 APP ID 配置云 API 公钥/密钥 配置优图 buck ...

  2. golang ---tcmalloc浅析

    总体结构 在tcmalloc内存管理的体系之中,一共有三个层次:ThreadCache.CentralCache.PageHeap,如上图所示.分配内存和释放内存的时候都是按从前到后的顺序,在各个层次 ...

  3. 9.1 翻译系列:数据注解特性之----Table【EF 6 Code-First 系列】

    原文地址:http://www.entityframeworktutorial.net/code-first/table-dataannotations-attribute-in-code-first ...

  4. Win10 设置窗口背景色

    Win10 的窗口背景色不能像Win7那样通过修改Windows的"窗口"配置来生效,只能是通过修改注册表的信息来修改Win10的窗口色. 1. 通过注册表来修改默认的窗口背景色( ...

  5. +: indexed part-select

    That syntax is called an indexed part-select. The first term is the bit offset and the second term i ...

  6. GNU make使用(二)

    [时间:2017-06] [状态:Open] [关键词:makefile,gcc,编译,shell命令,目标文件] 0 引言及目标 之前使用Makefile都是把源文件和目标文件放到同一个目录编译.近 ...

  7. JVM 内部原理(四)— 基本概念之 JVM 结构

    JVM 内部原理(四)- 基本概念之 JVM 结构 介绍 版本:Java SE 7 每位使用 Java 的程序员都知道 Java 字节码在 Java 运行时(JRE - Java Runtime En ...

  8. 教你一招:windows批处理中实现延时的办法

    五种方法可以实现批出里的延时,推荐使用方法一,该方法也是使用最多的. 方法一 用ping命令延迟(这是最简单而且是最常见的): @echo off echo "use ping to del ...

  9. hdoj:2040

    #include <iostream> #include <vector> using namespace std; vector<long> yueShu(lon ...

  10. Java知多少(76)语言包(java.lang)简介

    Java语言包(java.lang)定义了Java中的大多数基本类,由Java语言自动调用,不需要显示声明.该包中包含了Object类,Object类是整个类层次结构的根结点,同时还定义了基本数据类型 ...