標籤:
原文地址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-9
CreateZipFiles(sourceFilePath, zipStream);
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)
{
Crc32 crc = new Crc32();
string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
foreach (string file in filesArray)
{
if (Directory.Exists(file)) //如果當前是檔案夾,遞迴
{
CreateZipFiles(file, zipStream);
}
else //如果是檔案,開始壓縮
{
FileStream fileStream = File.OpenRead(file);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
string tempFile = file.Substring(sourceFilePath.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);
}
}
}
}
}
使用方法,在外部參考using ZipOneCode.ZipProvider 後,類似調用 ZipHelper.CreateZip(@"D:\Temp\forzip", @"D:\Temp2
\forzip.zip") 即可。
【轉】C#打包檔案夾成zip格式