从网上找来个ZipArchive来压缩和解压缩的类,供参考吧

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Windows.Forms;
  9. using Shared;
  10.  
  11. namespace Helpers
  12. {
  13. public static class ZipFileHelper
  14.  
  15. {
  16. #region Methods
  17.  
  18. /// <summary>
  19. /// 创建 zip 存档,该存档包含指定目录的文件和目录。
  20. /// </summary>
  21. /// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  22. /// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  23. /// <param name="compressionLevel"></param>
  24. /// <param name="includeBaseDirectory">压缩包中是否包含父目录</param>
  25. public static bool CreatZipFileFromDirectory(string sourceDirectoryName, string destinationArchiveFileName,
  26. CompressionLevel compressionLevel = CompressionLevel.NoCompression,
  27. bool includeBaseDirectory = true)
  28. {
  29. try
  30. {
  31. if (Directory.Exists(sourceDirectoryName)) //目录
  32. if (!File.Exists(destinationArchiveFileName))
  33. {
  34. ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
  35. compressionLevel, includeBaseDirectory);
  36. }
  37. else
  38. {
  39. var toZipFileDictionaryList = GetAllDirList(sourceDirectoryName, includeBaseDirectory);
  40.  
  41. using (
  42. var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
  43. )
  44. {
  45. foreach (var toZipFileKey in toZipFileDictionaryList.Keys)
  46. if (toZipFileKey != destinationArchiveFileName)
  47. {
  48. var toZipedFileName = Path.GetFileName(toZipFileKey);
  49. var toDelArchives = new List<ZipArchiveEntry>();
  50. foreach (var zipArchiveEntry in archive.Entries)
  51. if (toZipedFileName != null &&
  52. (zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
  53. toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  54. toDelArchives.Add(zipArchiveEntry);
  55. foreach (var zipArchiveEntry in toDelArchives)
  56. zipArchiveEntry.Delete();
  57. archive.CreateEntryFromFile(toZipFileKey, toZipFileDictionaryList[toZipFileKey],
  58. compressionLevel);
  59. }
  60. }
  61. }
  62. else if (File.Exists(sourceDirectoryName))
  63. if (!File.Exists(destinationArchiveFileName))
  64. ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName,
  65. compressionLevel, false);
  66. else
  67. using (
  68. var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update)
  69. )
  70. {
  71. if (sourceDirectoryName != destinationArchiveFileName)
  72. {
  73. var toZipedFileName = Path.GetFileName(sourceDirectoryName);
  74. var toDelArchives = new List<ZipArchiveEntry>();
  75. foreach (var zipArchiveEntry in archive.Entries)
  76. if (toZipedFileName != null &&
  77. (zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
  78. toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  79. toDelArchives.Add(zipArchiveEntry);
  80. foreach (var zipArchiveEntry in toDelArchives)
  81. zipArchiveEntry.Delete();
  82. archive.CreateEntryFromFile(sourceDirectoryName, toZipedFileName, compressionLevel);
  83. }
  84. }
  85. else
  86. return false;
  87. return true;
  88. }
  89. catch (Exception exception)
  90. {
  91. LogHelper.LogError("Error! ", exception);
  92. MessageBox.Show(exception.StackTrace, exception.Source);
  93. return false;
  94. }
  95. }
  96.  
  97. /// <summary>
  98. /// 创建 zip 存档,该存档包含指定目录的文件和目录。
  99. /// </summary>
  100. /// <param name="sourceDirectoryName">要存档的目录的路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  101. /// <param name="destinationArchiveFileName">要生成的存档路径,指定为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  102. /// <param name="compressionLevel"></param>
  103. public static bool CreatZipFileFromDictionary(Dictionary<string, string> sourceDirectoryName,
  104. string destinationArchiveFileName,
  105. CompressionLevel compressionLevel = CompressionLevel.NoCompression)
  106. {
  107. try
  108. {
  109. using (FileStream zipToOpen = new FileStream(destinationArchiveFileName, FileMode.OpenOrCreate))
  110. {
  111. using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
  112. {
  113. foreach (var toZipFileKey in sourceDirectoryName.Keys)
  114. if (toZipFileKey != destinationArchiveFileName)
  115. {
  116. var toZipedFileName = Path.GetFileName(toZipFileKey);
  117. var toDelArchives = new List<ZipArchiveEntry>();
  118. foreach (var zipArchiveEntry in archive.Entries)
  119. if (toZipedFileName != null &&
  120. (zipArchiveEntry.FullName.StartsWith(toZipedFileName) ||
  121. toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  122. toDelArchives.Add(zipArchiveEntry);
  123. foreach (var zipArchiveEntry in toDelArchives)
  124. zipArchiveEntry.Delete();
  125. archive.CreateEntryFromFile(toZipFileKey, sourceDirectoryName[toZipFileKey],
  126. compressionLevel);
  127. }
  128. }
  129. }
  130. return true;
  131. }
  132. catch (Exception exception)
  133. {
  134. LogHelper.LogError("Error! ", exception);
  135. MessageBox.Show(exception.StackTrace, exception.Source);
  136. return false;
  137. }
  138. }
  139.  
  140. /// <summary>
  141. /// 递归删除文件夹目录及文件
  142. /// </summary>
  143. /// <param name="baseDirectory"></param>
  144. /// <returns></returns>
  145. public static bool DeleteFolder(string baseDirectory)
  146. {
  147. var successed = true;
  148. try
  149. {
  150. if (Directory.Exists(baseDirectory)) //如果存在这个文件夹删除之
  151. {
  152. foreach (var directory in Directory.GetFileSystemEntries(baseDirectory))
  153. if (File.Exists(directory))
  154. File.Delete(directory); //直接删除其中的文件
  155. else
  156. successed = DeleteFolder(directory); //递归删除子文件夹
  157. Directory.Delete(baseDirectory); //删除已空文件夹
  158. }
  159. }
  160. catch (Exception exception)
  161. {
  162. LogHelper.LogError("Error! ", exception);
  163. successed = false;
  164. }
  165. return successed;
  166. }
  167.  
  168. /// <summary>
  169. /// 调用bat删除目录,以防止系统底层的异步删除机制
  170. /// </summary>
  171. /// <param name="dirPath"></param>
  172. /// <returns></returns>
  173. public static bool DeleteDirectoryWithCmd(string dirPath)
  174. {
  175. var process = new Process(); //string path = ...;//bat路径
  176. var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C rd /S /Q \"" + dirPath + "\"")
  177. {
  178. UseShellExecute = false,
  179. RedirectStandardOutput = true
  180. }; //第二个参数为传入的参数,string类型以空格分隔各个参数
  181. process.StartInfo = processStartInfo;
  182. process.Start();
  183. process.WaitForExit();
  184. var output = process.StandardOutput.ReadToEnd();
  185. if (string.IsNullOrWhiteSpace(output))
  186. return true;
  187. return false;
  188. }
  189.  
  190. /// <summary>
  191. /// 调用bat删除文件,以防止系统底层的异步删除机制
  192. /// </summary>
  193. /// <param name="filePath"></param>
  194. /// <returns></returns>
  195. public static bool DelFileWithCmd(string filePath)
  196. {
  197. var process = new Process(); //string path = ...;//bat路径
  198. var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C del /F /S /Q \"" + filePath + "\"")
  199. {
  200. UseShellExecute = false,
  201. RedirectStandardOutput = true
  202. }; //第二个参数为传入的参数,string类型以空格分隔各个参数
  203. process.StartInfo = processStartInfo;
  204. process.Start();
  205. process.WaitForExit();
  206. var output = process.StandardOutput.ReadToEnd();
  207. if (output.Contains(filePath))
  208. return true;
  209. return false;
  210. }
  211.  
  212. /// <summary>
  213. /// 获取目录下所有[文件名,要压缩的相对文件名]字典
  214. /// </summary>
  215. /// <param name="strBaseDir"></param>
  216. /// <param name="includeBaseDirectory"></param>
  217. /// <param name="namePrefix"></param>
  218. /// <returns></returns>
  219. public static Dictionary<string, string> GetAllDirList(string strBaseDir,
  220. bool includeBaseDirectory = false, string namePrefix = "")
  221. {
  222. var resultDictionary = new Dictionary<string, string>();
  223. var directoryInfo = new DirectoryInfo(strBaseDir);
  224. var directories = directoryInfo.GetDirectories();
  225. var fileInfos = directoryInfo.GetFiles();
  226. if (includeBaseDirectory)
  227. namePrefix += directoryInfo.Name + "\\";
  228. foreach (var directory in directories)
  229. resultDictionary =
  230. resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix))
  231. .ToDictionary(k => k.Key, k => k.Value); //.FullName是某个子目录的绝对地址,
  232. foreach (var fileInfo in fileInfos)
  233. if (!resultDictionary.ContainsKey(fileInfo.FullName))
  234. resultDictionary.Add(fileInfo.FullName, namePrefix + fileInfo.Name);
  235. return resultDictionary;
  236. }
  237.  
  238. /// <summary>
  239. /// Zip解压并更新目标文件
  240. /// </summary>
  241. /// <param name="zipFilePath">Zip压缩包路径</param>
  242. /// <param name="unZipDir">解压目标路径</param>
  243. /// <returns></returns>
  244. public static bool UnZip(string zipFilePath, string unZipDir)
  245. {
  246. bool resualt;
  247. try
  248. {
  249. unZipDir = unZipDir.EndsWith(@"\") ? unZipDir : unZipDir + @"\";
  250. var directoryInfo = new DirectoryInfo(unZipDir);
  251. if (!directoryInfo.Exists)
  252. directoryInfo.Create();
  253. var fileInfo = new FileInfo(zipFilePath);
  254. if (!fileInfo.Exists)
  255. return false;
  256. using (
  257. var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite,
  258. FileShare.Read))
  259. {
  260. using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
  261. {
  262. foreach (var zipArchiveEntry in archive.Entries)
  263. if (!zipArchiveEntry.FullName.EndsWith("/"))
  264. {
  265. var entryFilePath = Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"),
  266. @"^\\*", "");
  267. var filePath = directoryInfo + entryFilePath; //设置解压路径
  268. var content = new byte[zipArchiveEntry.Length];
  269. zipArchiveEntry.Open().Read(content, , content.Length);
  270.  
  271. if (File.Exists(filePath) && content.Length == new FileInfo(filePath).Length)
  272. continue; //跳过相同的文件,否则覆盖更新
  273.  
  274. var sameDirectoryNameFilePath = new DirectoryInfo(filePath);
  275. if (sameDirectoryNameFilePath.Exists)
  276. {
  277. sameDirectoryNameFilePath.Delete(true);
  278. DeleteDirectoryWithCmd(filePath);
  279. /*if (!DeleteDirectoryWithCmd(filePath))
  280. {
  281. Console.WriteLine(filePath + "删除失败");
  282. resualt = false;
  283. break;
  284. }*/
  285. }
  286. var sameFileNameFilePath = new FileInfo(filePath);
  287. if (sameFileNameFilePath.Exists)
  288. {
  289. sameFileNameFilePath.Delete();
  290. DelFileWithCmd(filePath);
  291. /*if (!DelFileWithCmd(filePath))
  292. {
  293. Console.WriteLine(filePath + "删除失败");
  294. resualt = false;
  295. break;
  296. }*/
  297. }
  298. var greatFolder = Directory.GetParent(filePath);
  299. if (!greatFolder.Exists) greatFolder.Create();
  300. File.WriteAllBytes(filePath, content);
  301. }
  302. }
  303. }
  304. resualt = true;
  305. }
  306. catch
  307. (Exception exception)
  308. {
  309. LogHelper.LogError("Error! ", exception);
  310. resualt = false;
  311. }
  312. return resualt;
  313. }
  314.  
  315. #endregion
  316. }
  317. }

出处:https://www.cnblogs.com/Chary/p/No0000DF.html

==============================================

自己在项目中的使用:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Linq;
  6. using System.Diagnostics;
  7. using System.Text.RegularExpressions;
  8. using System.Windows.Forms;
  9.  
  10. namespace Car.AutoUpdate.Comm
  11. {
  12. public class ZipArchiveHelper
  13. {
  14.  
  15. #region Methods
  16.  
  17. /// <summary>
  18. /// 创建 zip 存档,该文档包含指定目录的文件和子目录。
  19. /// </summary>
  20. /// <param name="sourceDirectoryName">将要压缩存档的文件目录的路径,可以为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  21. /// <param name="destinationArchiveFileName">将要生成的压缩包的存档路径,可以为相对路径或绝对路径。相对路径是指相对于当前工作目录的路径。</param>
  22. /// <param name="compressionLevel">指示压缩操作是强调速度还是强调压缩大小的枚举值</param>
  23. /// <param name="includeBaseDirectory">压缩包中是否包含父目录</param>
  24. public static bool CreatZip(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel = CompressionLevel.NoCompression, bool includeBaseDirectory = true)
  25. {
  26. try
  27. {
  28. if (Directory.Exists(sourceDirectoryName))
  29. if (!File.Exists(destinationArchiveFileName))
  30. {
  31. ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory);
  32. }
  33. else
  34. {
  35. var toZipFileDictionaryList = GetAllDirList(sourceDirectoryName, includeBaseDirectory);
  36. using (var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update))
  37. {
  38. foreach (var toZipFileKey in toZipFileDictionaryList.Keys)
  39. if (toZipFileKey != destinationArchiveFileName)
  40. {
  41. var toZipedFileName = Path.GetFileName(toZipFileKey);
  42. var toDelArchives = new List<ZipArchiveEntry>();
  43. foreach (var zipArchiveEntry in archive.Entries)
  44. if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  45. toDelArchives.Add(zipArchiveEntry);
  46. foreach (var zipArchiveEntry in toDelArchives)
  47. zipArchiveEntry.Delete();
  48. archive.CreateEntryFromFile(toZipFileKey, toZipFileDictionaryList[toZipFileKey], compressionLevel);
  49. }
  50. }
  51. }
  52. else if (File.Exists(sourceDirectoryName))
  53. if (!File.Exists(destinationArchiveFileName))
  54. ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, false);
  55. else
  56. using (var archive = ZipFile.Open(destinationArchiveFileName, ZipArchiveMode.Update))
  57. {
  58. if (sourceDirectoryName != destinationArchiveFileName)
  59. {
  60. var toZipedFileName = Path.GetFileName(sourceDirectoryName);
  61. var toDelArchives = new List<ZipArchiveEntry>();
  62. foreach (var zipArchiveEntry in archive.Entries)
  63. if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  64. toDelArchives.Add(zipArchiveEntry);
  65. foreach (var zipArchiveEntry in toDelArchives)
  66. zipArchiveEntry.Delete();
  67. archive.CreateEntryFromFile(sourceDirectoryName, toZipedFileName, compressionLevel);
  68. }
  69. }
  70. else
  71. return false;
  72. return true;
  73. }
  74. catch (Exception ex)
  75. {
  76. LogHelper.Error("Error! ", ex);
  77. //MessageBox.Show(ex.StackTrace, ex.Source);
  78. UtilityHelper.ShowMessageDialog(ex.StackTrace);
  79. return false;
  80. }
  81. }
  82.  
  83. /// <summary>
  84. /// 创建 zip 存档,该存档包含指定目录的文件和目录。
  85. /// </summary>
  86. /// <param name="sourceDirectoryName">将要压缩存档的文件目录的路径,可以为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  87. /// <param name="destinationArchiveFileName">将要生成的压缩包的存档路径,可以为相对路径或绝对路径。 相对路径是指相对于当前工作目录的路径。</param>
  88. /// <param name="compressionLevel">指示压缩操作是强调速度还是强调压缩大小的枚举值</param>
  89. public static bool CreatZip(Dictionary<string, string> sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
  90. {
  91. try
  92. {
  93. using (FileStream zipToOpen = new FileStream(destinationArchiveFileName, FileMode.OpenOrCreate))
  94. {
  95. using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
  96. {
  97. foreach (var toZipFileKey in sourceDirectoryName.Keys)
  98. if (toZipFileKey != destinationArchiveFileName)
  99. {
  100. var toZipedFileName = Path.GetFileName(toZipFileKey);
  101. var toDelArchives = new List<ZipArchiveEntry>();
  102. foreach (var zipArchiveEntry in archive.Entries)
  103. if (toZipedFileName != null && (zipArchiveEntry.FullName.StartsWith(toZipedFileName) || toZipedFileName.StartsWith(zipArchiveEntry.FullName)))
  104. toDelArchives.Add(zipArchiveEntry);
  105. foreach (var zipArchiveEntry in toDelArchives)
  106. zipArchiveEntry.Delete();
  107. archive.CreateEntryFromFile(toZipFileKey, sourceDirectoryName[toZipFileKey], compressionLevel);
  108. }
  109. }
  110. }
  111. return true;
  112. }
  113. catch (Exception ex)
  114. {
  115. LogHelper.Error("Error! ", ex);
  116. UtilityHelper.ShowMessageDialog(ex.StackTrace);
  117. return false;
  118. }
  119. }
  120.  
  121. /// <summary>
  122. /// 递归删除磁盘上的指定文件夹目录及文件
  123. /// </summary>
  124. /// <param name="baseDirectory"></param>
  125. /// <returns></returns>
  126. private static bool DeleteFolder(string baseDirectory)
  127. {
  128. var successed = true;
  129. try
  130. {
  131. if (Directory.Exists(baseDirectory)) //如果存在这个文件夹删除之
  132. {
  133. foreach (var directory in Directory.GetFileSystemEntries(baseDirectory))
  134. if (File.Exists(directory))
  135. File.Delete(directory); //直接删除其中的文件
  136. else
  137. successed = DeleteFolder(directory); //递归删除子文件夹
  138. Directory.Delete(baseDirectory); //删除已空文件夹
  139. }
  140. }
  141. catch (Exception ex)
  142. {
  143. LogHelper.Error("Error! ", ex);
  144. successed = false;
  145. }
  146. return successed;
  147. }
  148.  
  149. /// <summary>
  150. /// 调用CMD,命令行删除磁盘上的指定目录,以防止系统底层的异步删除机制
  151. /// </summary>
  152. /// <param name="dirPath"></param>
  153. /// <returns></returns>
  154. private static bool DeleteDirectoryWithCmd(string dirPath)
  155. {
  156. var process = new Process();
  157. //ProcessStartInfo构造方法的第二个参数是执行第一个命令的所需要传入的参数,以空格分隔各个参数
  158. var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C rd /S /Q \"" + dirPath + "\"") { UseShellExecute = false, RedirectStandardOutput = true };
  159. process.StartInfo = processStartInfo;
  160. process.Start();
  161. process.WaitForExit();
  162. var output = process.StandardOutput.ReadToEnd();
  163. if (string.IsNullOrWhiteSpace(output))
  164. return true;
  165. return false;
  166. }
  167.  
  168. /// <summary>
  169. /// 调用CMD,命令行删除磁盘上的指定目录,以防止系统底层的异步删除机制
  170. /// </summary>
  171. /// <param name="filePath"></param>
  172. /// <returns></returns>
  173. private static bool DelFileWithCmd(string filePath)
  174. {
  175. var process = new Process();
  176. //ProcessStartInfo构造方法的第二个参数是执行第一个命令的所需要传入的参数,以空格分隔各个参数
  177. var processStartInfo = new ProcessStartInfo("CMD.EXE", "/C del /F /S /Q \"" + filePath + "\"") { UseShellExecute = false, RedirectStandardOutput = true };
  178. process.StartInfo = processStartInfo;
  179. process.Start();
  180. process.WaitForExit();
  181. var output = process.StandardOutput.ReadToEnd();
  182. if (output.Contains(filePath))
  183. return true;
  184. return false;
  185. }
  186.  
  187. /// <summary>
  188. /// 递归获取磁盘上的指定目录下所有文件的集合,返回类型是:字典[文件名,要压缩的相对文件名]
  189. /// </summary>
  190. /// <param name="strBaseDir"></param>
  191. /// <param name="includeBaseDirectory"></param>
  192. /// <param name="namePrefix"></param>
  193. /// <returns></returns>
  194. private static Dictionary<string, string> GetAllDirList(string strBaseDir, bool includeBaseDirectory = false, string namePrefix = "")
  195. {
  196. var resultDictionary = new Dictionary<string, string>();
  197. var directoryInfo = new DirectoryInfo(strBaseDir);
  198. var directories = directoryInfo.GetDirectories();
  199. var fileInfos = directoryInfo.GetFiles();
  200. if (includeBaseDirectory)
  201. namePrefix += directoryInfo.Name + "\\";
  202. foreach (var directory in directories)
  203. resultDictionary = resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix)).ToDictionary(k => k.Key, k => k.Value); //FullName是某个子目录的绝对地址,
  204. foreach (var fileInfo in fileInfos)
  205. if (!resultDictionary.ContainsKey(fileInfo.FullName))
  206. resultDictionary.Add(fileInfo.FullName, namePrefix + fileInfo.Name);
  207. return resultDictionary;
  208. }
  209.  
  210. /// <summary>
  211. /// 解压Zip文件,并覆盖保存到指定的目标路径文件夹下
  212. /// </summary>
  213. /// <param name="zipFilePath">将要解压缩的zip文件的路径</param>
  214. /// <param name="unZipDir">解压后将zip中的文件存储到磁盘的目标路径</param>
  215. /// <returns></returns>
  216. public static bool UnZip(string zipFilePath, string unZipDir)
  217. {
  218. bool resualt;
  219. try
  220. {
  221. unZipDir = unZipDir.EndsWith(@"\") ? unZipDir : unZipDir + @"\";
  222. var directoryInfo = new DirectoryInfo(unZipDir);
  223. if (!directoryInfo.Exists)
  224. directoryInfo.Create();
  225. var fileInfo = new FileInfo(zipFilePath);
  226. if (!fileInfo.Exists)
  227. return false;
  228. using (var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
  229. {
  230. using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
  231. {
  232. foreach (var zipArchiveEntry in archive.Entries)
  233. if (!zipArchiveEntry.FullName.EndsWith("/"))
  234. {
  235. var entryFilePath = Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"), @"^\\*", "");
  236. var filePath = directoryInfo + entryFilePath; //设置解压路径
  237. var content = new byte[zipArchiveEntry.Length];
  238. zipArchiveEntry.Open().Read(content, , content.Length);
  239.  
  240. // mq 2019-06-14: 注销下面的代码,全部覆盖现有文件
  241. //if (File.Exists(filePath) && content.Length == new FileInfo(filePath).Length)
  242. //{
  243. // continue; //跳过相同的文件,否则覆盖更新
  244. //}
  245. //var sameDirectoryNameFilePath = new DirectoryInfo(filePath);
  246. //if (sameDirectoryNameFilePath.Exists)
  247. //{
  248. // sameDirectoryNameFilePath.Delete(true);
  249. // DeleteDirectoryWithCmd(filePath);
  250. //}
  251. //var sameFileNameFilePath = new FileInfo(filePath);
  252. //if (sameFileNameFilePath.Exists)
  253. //{
  254. // sameFileNameFilePath.Delete();
  255. // DelFileWithCmd(filePath);
  256. // /*if (!DelFileWithCmd(filePath))
  257. // {
  258. // Console.WriteLine(filePath + "删除失败");
  259. // resualt = false;
  260. // break;
  261. // }*/
  262. //}
  263.  
  264. var greatFolder = Directory.GetParent(filePath);
  265. if (!greatFolder.Exists)
  266. greatFolder.Create();
  267. File.WriteAllBytes(filePath, content);
  268. }
  269. }
  270. }
  271. resualt = true;
  272. }
  273. catch (Exception ex)
  274. {
  275. LogHelper.Error("Error! ", ex);
  276. resualt = false;
  277. }
  278. return resualt;
  279. }
  280.  
  281. /// <summary>
  282. /// 获取Zip压缩包中的文件列表
  283. /// </summary>
  284. /// <param name="zipFilePath">Zip压缩包文件的物理路径</param>
  285. /// <returns></returns>
  286. public static List<string> GetZipFileList(string zipFilePath)
  287. {
  288. List<string> fList = new List<string>();
  289. if (!File.Exists(zipFilePath))
  290. return fList;
  291. try
  292. {
  293. using (var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  294. {
  295. using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
  296. {
  297. foreach (var zipArchiveEntry in archive.Entries)
  298. if (!zipArchiveEntry.FullName.EndsWith("/"))
  299. fList.Add(Regex.Replace(zipArchiveEntry.FullName.Replace("/", @"\"), @"^\\*", ""));
  300. }
  301. }
  302. }
  303. catch (Exception ex)
  304. {
  305. LogHelper.Error("Error! ", ex);
  306. }
  307. return fList;
  308. }
  309.  
  310. #endregion
  311. }
  312. }

C# ZipHelper C#公共类 -- ZipArchive实现压缩和解压的更多相关文章

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

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

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

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

  3. ZipHelper 压缩和解压帮助类

    ZipHelper 压缩和解压帮助类 关于本文档的说明 本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的 欢迎传播 ...

  4. 【C#公共帮助类】WinRarHelper帮助类,实现文件或文件夹压缩和解压,实战干货

    关于本文档的说明 本文档使用WinRAR方式来进行简单的压缩和解压动作,纯干货,实际项目这种压缩方式用的少一点,一般我会使用第三方的压缩dll来实现,就如同我上一个压缩类博客,压缩的是zip文件htt ...

  5. c#自带压缩类实现的多文件压缩和解压

    用c#自带的System.IO.Compression命名空间下的压缩类实现的多文件压缩和解压功能,缺点是多文件压缩包的解压只能调用自身的解压方法,和现有的压缩软件不兼容.下面的代码没有把多文件的目录 ...

  6. 利用c#自带的类对文件进行压缩和解压处理

    在做网络传输文件的小例子的时候,当传输的文件比较大的时候,我们通常都是将文件经过压缩之后才进行传输,以前都是利用第三方插件来对文件进行压缩的,但是现在我发现了c#自带的类库也能够实现文件的压缩,实际上 ...

  7. Linux 时间日期类、搜索查找类、 压缩和解压类指令

    l 时间日期类 date指令-显示当前日期 基本语法 1) date (功能描述:显示当前时间) 2) date +%Y (功能描述:显示当前年份) 3) date +%m (功能描述:显示当前月份) ...

  8. Linux时间日期类,压缩和解压类

    一.时间日期类 1.data指令 1.基本指令 date 显示当前日期 data +%Y 显示当前年份 data +%m 显示当前月份 data +%d 显示当前天 data +%Y-%m-%d %H ...

  9. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

随机推荐

  1. vs2015调试iisexpress无法启动的问题解决方案整理

    我上传的项目代码被同事下载之后使用iisexpress调试一直报错,iisexpress无法启动只能用自己本地的iis,我本地的代码却没问题,试了两种解决办法,问题解决了,在此记录一下也总结一下 方法 ...

  2. sqlserver数据库中sql的使用

    目录: 1. 分组排序更新 2. 将查询结果插入到新的表中 3. 创建/更新存储过程 4. 创建/更新视图 5. 插入数据 6. 增加表格的列 7. 创建表格 8. 创建索引 9. 递归查询 1. 分 ...

  3. TCP/IP三次握手和四次挥手

    原博链接:https://www.cnblogs.com/Andya/p/7272462.html

  4. [Java] 项目红色叹号 案例1则

    一般红色叹号是build path出错. 除了检查出错的library外,还要注意Order an Export选项中未勾选的Library. 之前导入项目后,没有勾选JRE和Maven Depend ...

  5. eolinker 安装时遇到的坑

    Access denied for user 'root'@'localhost' (using password:YES) 从githup 上下载的代码,直接把release 里的文件发布到服务器上 ...

  6. Bootstrap框架整理

    bootstrap框架的介绍 栅格系统 bootstrap框架把整个浏览器的宽度分为12列,并能适配各种屏幕的尺寸大小进行相应的匹配,达到调节页面大小的效果. 首先需要放置一个容器div,class= ...

  7. 原生sql实现restful接口调用

    index.php <?php include './Request.php';include './Response.php';//获取数据$data=Request::getRequest( ...

  8. 【lintcode13】字符串查找

    问题: 对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始).如果不存在,则返回 -1. 样例:如果 ...

  9. Harbor使用 -- 修改80端口

    在公网上,一般情况下都不暴露默认端口,避免被攻击! 以下修改harbor的默认80端口为其他端口! 我这里示例修改为1180端口! 注意:以下步骤都是在harbor目录下操作!!! 1.修改docke ...

  10. sin n次方 x 的降幂公式

    A(n) = ∫ sinⁿx dx= ∫ sinⁿ⁻¹xsinx dx= - ∫ sinⁿ⁻¹x d(cosx)= - sinⁿ⁻¹xcosx + ∫ cosx • d(sinⁿ⁻¹)= - sinⁿ ...