C#利用ICSharpCode.SharpZipLib.dll壓縮檔和解壓檔案

來源:互聯網
上載者:User

這兩個類是從網上找來的,修改了一下,改為自己所需要的,測試通過.壓縮後的檔案為.zip
感覺還不錯,所以轉載一下與大家共用
/// <summary>
 /// 壓縮檔
 /// </summary>

using System;
using System.IO;

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;

namespace FtpResume.Utility
{
    public class ZipClass
    {
        public string cutStr = "";

        public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
        {
            //如果檔案沒有找到則報錯。
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
            }

            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipEntry ZipEntry = new ZipEntry("ZippedFile");
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[BlockSize];
            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
            ZipStream.Write(buffer, 0, size);
            try
            {
                while (size < StreamToZip.Length)
                {
                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                    ZipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            ZipStream.Finish();
            ZipStream.Close();
            StreamToZip.Close();
        }

        //Get all DirectoryInfo
        private void direct(DirectoryInfo di, ref ZipOutputStream s, Crc32 crc)
        {
            //DirectoryInfo di = new DirectoryInfo(filenames);
            DirectoryInfo[] dirs = di.GetDirectories("*");

            //遍曆目錄下面的所有的子目錄
            foreach (DirectoryInfo dirNext in dirs)
            {
                //將該目錄下的所有檔案添加到 ZipOutputStream s 壓縮流裡面
                FileInfo[] a = dirNext.GetFiles();
                this.writeStream(ref s, a, crc);

                //遞迴調用直到把所有的目錄遍曆完成
                direct(dirNext, ref s, crc);
            }
        }

        private void writeStream(ref ZipOutputStream s, FileInfo[] a, Crc32 crc)
        {
            foreach (FileInfo fi in a)
            {
                //string fifn = fi.FullName;
                FileStream fs = fi.OpenRead();

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);

                //ZipEntry entry = new ZipEntry(file);    Path.GetFileName(file)
                string file = fi.FullName;
                file = file.Replace(cutStr, "");

                ZipEntry entry = new ZipEntry(file);

                entry.DateTime = DateTime.Now;

                // set Size and the crc, because the information
                // about the size and crc should be stored in the header
                // if it is not set it is automatically written in the footer.
                // (in this case size == crc == -1 in the header)
                // Some ZIP programs have problems with zip files that don't store
                // the size and crc in the header.
                entry.Size = fs.Length;
                fs.Close();

                crc.Reset();
                crc.Update(buffer);

                entry.Crc = crc.Value;

                s.PutNextEntry(entry);

                s.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// 壓縮指定目錄下指定檔案(包括子目錄下的檔案)
        /// </summary>
        /// <param name="zippath">args[0]為你要壓縮的目錄所在的路徑
        /// 例如:D:\\temp\\   (注意temp 後面加 \\ 但是你寫程式的時候怎麼修改都可以)</param>
        /// <param name="zipfilename">args[1]為壓縮後的檔案名稱及其路徑
        /// 例如:D:\\temp.zip</param>
        /// <param name="fileFilter">檔案過濾, 例如*.xml,這樣只壓縮.xml檔案.</param>
        ///
        public bool ZipFileMain(string zippath, string zipfilename, string fileFilter)
        {
            try
            {
                //string filenames = Directory.GetFiles(args[0]);

                Crc32 crc = new Crc32();
                ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename));

                s.SetLevel(6); // 0 - store only to 9 - means best compression

                DirectoryInfo di = new DirectoryInfo(zippath);

                FileInfo[] a = di.GetFiles(fileFilter);

                cutStr = zippath.Trim();
                //壓縮這個目錄下的所有檔案
                writeStream(ref s, a, crc);
                //壓縮這個目錄下子目錄及其檔案
                direct(di, ref s, crc);

                s.Finish();
                s.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}

 

///<summary>
///解壓縮檔案
///</summary>
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;

using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;

namespace FtpResume.Utility
{
    public class UnZipClass
    {
        /// <summary>
        /// 解壓縮檔案(壓縮檔中含有子目錄)
        /// </summary>
        /// <param name="zipfilepath">待解壓縮的檔案路徑</param>
        /// <param name="unzippath">解壓縮到指定目錄</param>
        public void UnZip(string zipfilepath, string unzippath)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(unzippath);
                string fileName = Path.GetFileName(theEntry.Name);

                //產生解壓目錄
                Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    //如果檔案的壓縮後大小為0那麼說明這個檔案是空的,因此不需要進行讀出寫入
                    if (theEntry.CompressedSize == 0)
                        break;
                    //解壓檔案到指定的目錄
                    directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
                    //建立下面的目錄和子目錄
                    Directory.CreateDirectory(directoryName);

                    FileStream streamWriter = File.Create(unzippath + theEntry.Name);

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            s.Close();
        }
    }
}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.