C#打包檔案夾成zip格式(包括檔案夾和子檔案夾下的所有檔案)

來源:互聯網
上載者:User

之前不喜歡玩部落格,這次在部落格園也註冊了這個部落格玩玩。
可是沒什麼內容,所以想隨便添加點什麼吧。

最近在微軟開發的幾個小工具,大多跟檔案操作/IO相關,所以準備這兩天整理一下,把一些也許可以和大家分享的東西貼出來,希望對於一些C#的初學者有一些協助吧!
(更多範例程式碼,可以訪問微軟學習者協助網站 Code smaples from microsoft: http://1code.codeplex.com ,下載微軟的All-in-onecode framework  ,這是我最近在Microsoft要接手負責開發的一個供開發人員學習的工具,裡面可以搜尋到有很多範例程式碼可供學習者參考。)

 

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, 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);                }            }        }    }}

 

 

使用方法,在外部參考using ZipOneCode.ZipProvider 後,類似調用 ZipHelper.CreateZip(@"D:\Temp\forzip", @"D:\Temp2\forzip.zip") 即可。

注意在調用之前,考慮注意一些異常情況的判斷,比如源檔案路徑是否存在等。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.