C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)

C#打包zip文件可以调用现成的第三方dll,事半功倍,而且该dll完全免费,下载地址:SharpZipLib

下载完解压缩后,把 ICSharpCode.SharpZipLib.dll
拷贝到当前项目的目录下(如果偷懒的话,可以直接拷贝到当前项目的bin/Debug目录下),在VS打开的项目引用上右键添加引用
ICSharpCode.SharpZipLib.dll

然后,在VS打开的项目上右键新建一个类,命名为 ZipHelper.cs,把类里面的所有code清空,复制以下代码,粘贴:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Diagnostics;
  7. using ICSharpCode.SharpZipLib;
  8. using ICSharpCode.SharpZipLib.Zip;
  9. using ICSharpCode.SharpZipLib.Checksums;
  10. using ICSharpCode.SharpZipLib.Core;
  11. namespace ZipOneCode.ZipProvider
  12. {
  13. public class ZipHelper
  14. {
  15. /// <summary>
  16. /// 压缩文件
  17. /// </summary>
  18. /// <param name="sourceFilePath"></param>
  19. /// <param name="destinationZipFilePath"></param>
  20. public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
  21. {
  22. if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
  23. sourceFilePath += System.IO.Path.DirectorySeparatorChar;
  24. ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
  25. zipStream.SetLevel(6); // 压缩级别 0-9
  26. CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);
  27. zipStream.Finish();
  28. zipStream.Close();
  29. }
  30. /// <summary>
  31. /// 递归压缩文件
  32. /// </summary>
  33. /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
  34. /// <param name="zipStream">打包结果的zip文件路径(类似 D:/WorkSpace/a.zip),全路径包括文件名和.zip扩展名</param>
  35. /// <param name="staticFile"></param>
  36. private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
  37. {
  38. Crc32 crc = new Crc32();
  39. string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
  40. foreach (string file in filesArray)
  41. {
  42. if (Directory.Exists(file)) //如果当前是文件夹,递归
  43. {
  44. CreateZipFiles(file, zipStream, staticFile);
  45. }
  46. else //如果是文件,开始压缩
  47. {
  48. FileStream fileStream = File.OpenRead(file);
  49. byte[] buffer = new byte[fileStream.Length];
  50. fileStream.Read(buffer, 0, buffer.Length);
  51. string tempFile = file.Substring(staticFile.LastIndexOf("//") + 1);
  52. ZipEntry entry = new ZipEntry(tempFile);
  53. entry.DateTime = DateTime.Now;
  54. entry.Size = fileStream.Length;
  55. fileStream.Close();
  56. crc.Reset();
  57. crc.Update(buffer);
  58. entry.Crc = crc.Value;
  59. zipStream.PutNextEntry(entry);
  60. zipStream.Write(buffer, 0, buffer.Length);
  61. }
  62. }
  63. }
  64. }
  65. }

原文地址:http://www.dotnetbbs.com/read.php?tid-59.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值