C#中用SharpZipLib.dll实现压缩解压 顺序压缩

原文//第一段代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.Zip;

namespace PlayEdit.ClassObj
{
    //压缩类

    class ClassZip
    {
        ///



        /// 递归压缩文件夹方法

        ///


        /// 

        /// 

        /// 

        private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
        {
            bool res = true;
            string[] folders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {

                //创建当前文件夹

                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建

                s.PutNextEntry(entry);
                s.Flush();


                //先压缩文件,再递归压缩文件夹

                filenames = Directory.GetFiles(FolderToZip);
                foreach (string file in filenames)
                {
                    //打开压缩文件

                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }


            folders = Directory.GetDirectories(FolderToZip);
            foreach (string folder in folders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                {
                    return false;
                }
            }

            return res;
        }

        ///

        /// 压缩目录

        ///

        /// 待压缩的文件夹,全路径格式

        /// 压缩后的文件名,全路径格式

        /// 

        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
            {
                return false;
            }

            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(level);
            res = ZipFileDictory(FolderToZip, s, "");

            s.Finish();
            s.Close();

            return res;
        }

        ///

        /// 压缩文件

        ///

        /// 要进行压缩的文件名

        /// 压缩后生成的压缩文件名

        /// 

        private static bool ZipFile(string FileToZip, string ZipedFile, int level)
        {
            //如果文件没有找到,则报错

            if (!File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            }
            //FileStream fs = null;

            FileStream ZipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry ZipEntry = null;
            bool res = true;
            try
            {
                ZipFile = File.OpenRead(FileToZip);
                byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 0, buffer.Length);
                ZipFile.Close();

                ZipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(ZipFile);
                ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(level);

                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            return res;
        }
        ///

        /// 压缩文件 和 文件夹

        ///

        /// 待压缩的文件或文件夹,全路径格式

        /// 压缩后生成的压缩文件名,全路径格式

        /// 

        public static bool Zip(String FileToZip, String ZipedFile, int level)
        {
            if (Directory.Exists(FileToZip))
            {
                return ZipFileDictory(FileToZip, ZipedFile, level);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, ZipedFile, level);
            }
            else
            {
                return false;
            }
        }
    }
    ///

    /// 解压类

    ///

    public class UnZipClass
    {
        ///

        /// 解压功能(解压压缩文件到指定目录)

        ///

        /// 待解压的文件

        /// 指定解压目标目录

        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }

            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }

            ZipInputStream s = null;
            ZipEntry theEntry = null;

            string fileName;
            FileStream streamWriter = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        ///判断文件路径是否是文件夹

                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        streamWriter = File.Create(fileName);
                        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;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (!= null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
    }

}


//第二段代码:

/**////



 2 /// Create a zip archive.

 3 ///


 4 /// The filename.

 5 /// The directory to zip. 

 6 public static void PackFiles(string filename, string directory)
 7 {
 8 try
 9 {
10 FastZip fz = new FastZip();
11 fz.CreateEmptyDirectories = true;
12 fz.CreateZip(filename, directory, true, "");
13 fz = null;
14 }
15 catch (Exception)
16 {
17 throw;
18 }
19 }
20
21 /**////

22 /// Unpacks the files.

23 ///

24 /// The file.

25 /// if succeed return true,otherwise false.

26 public static bool UnpackFiles(string file, string dir)
27 {
28 try
29 {
30 if (!Directory.Exists(dir))
31 Directory.CreateDirectory(dir);
32
33 ZipInputStream s = new ZipInputStream(File.OpenRead(file));
34
35 ZipEntry theEntry;
36 while ((theEntry = s.GetNextEntry()) != null)
37 {
38
39 string directoryName = Path.GetDirectoryName(theEntry.Name);
40 string fileName = Path.GetFileName(theEntry.Name);
41
42 if (directoryName != String.Empty)
43 Directory.CreateDirectory(dir + directoryName);
44
45 if (fileName != String.Empty)
46 {
47 
FileStream streamWriter = File.Create(Path.Combine(dir,theEntry.Name) );
48
49 int size = 2048;
50 byte[] data = new byte[2048];
51 while (true)
52 {
53 size = s.Read(data, 0, data.Length);
54 if (size > 0)
55 {
56 streamWriter.Write(data, 0, size);
57 }
58 else
59 {
60 break;
61 }
62 }
63
64 streamWriter.Close();
65 }
66 }
67 s.Close();
68 return true;
69 }
70 catch (Exception)
71 {
72 throw;
73 }


//第三段代码:

///



 /// 压缩文件

 ///



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

        ///

        /// 压缩指定目录下指定文件(包括子目录下的文件)

        ///

        /// args[0]为你要压缩的目录所在的路径

        /// 例如:D:\\temp\\ (注意temp 后面加 \\ 但是你写程序的时候怎么修改都可以)

        /// args[1]为压缩后的文件名及其路径

        /// 例如:D:\\temp.zip

        /// 文件过滤, 例如*.xml,这样只压缩.xml文件.

        ///

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


 

///

///解压缩文件

///

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
    {
        ///

        /// 解压缩文件(压缩文件中含有子目录)

        ///

        /// 待解压缩的文件路径

        /// 解压缩到指定目录

        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();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值