生活随笔
收集整理的這篇文章主要介紹了
【转】C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C#打包zip文件可以調用現成的第三方dll,事半功倍,而且該dll完全免費,下載地址:SharpZipLib
下載完解壓縮后,把 ICSharpCode.SharpZipLib.dll?
拷貝到當前項目的目錄下(如果偷懶的話,可以直接拷貝到當前項目的bin/Debug目錄下),在VS打開的項目引用上右鍵添加引用?
ICSharpCode.SharpZipLib.dll?
然后,在VS打開的項目上右鍵新建一個類,命名為 ZipHelper.cs,把類里面的所有code清空,復制以下代碼,粘貼:
復制代碼
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Diagnostics;using ICSharpCode.SharpZipLib;using ICSharpCode.SharpZipLib.Zip;using ICSharpCode.SharpZipLib.Checksums;using ICSharpCode.SharpZipLib.Core;namespace ZipOneCode.ZipProvider{public class ZipHelper{/// <summary>/// 壓縮文件/// </summary>/// <param name="sourceFilePath"></param>/// <param name="destinationZipFilePath"></param>public static void CreateZip(string sourceFilePath, string destinationZipFilePath){if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)sourceFilePath += System.IO.Path.DirectorySeparatorChar;ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));zipStream.SetLevel(6); // 壓縮級別 0-9CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);zipStream.Finish();zipStream.Close();}/// <summary>/// 遞歸壓縮文件/// </summary>/// <param name="sourceFilePath">待壓縮的文件或文件夾路徑</param>/// <param name="zipStream">打包結果的zip文件路徑(類似 D:/WorkSpace/a.zip),全路徑包括文件名和.zip擴展名</param>/// <param name="staticFile"></param>private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile){Crc32 crc = new Crc32();string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);foreach (string file in filesArray){if (Directory.Exists(file)) //如果當前是文件夾,遞歸{CreateZipFiles(file, zipStream, staticFile);}else //如果是文件,開始壓縮{FileStream fileStream = File.OpenRead(file);byte[] buffer = new byte[fileStream.Length];fileStream.Read(buffer, 0, buffer.Length);string tempFile = file.Substring(staticFile.LastIndexOf("//") + 1);ZipEntry entry = new ZipEntry(tempFile);entry.DateTime = DateTime.Now;entry.Size = fileStream.Length;fileStream.Close();crc.Reset();crc.Update(buffer);entry.Crc = crc.Value;zipStream.PutNextEntry(entry);zipStream.Write(buffer, 0, buffer.Length);}}}}}
原文地址:http://www.dotnetbbs.com/read.php?tid-59.html
總結
以上是生活随笔為你收集整理的【转】C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。