C#使用ICSharpCode.SharpZipLib压缩文件[转]

简介:

本文来自CSDN博客,出处:http://blog.csdn.net/venus0314/archive/2006/09/25/1280610.aspx

 

一直以来都是采用WinZIP进行压缩的,调用起来方便,而且公司也有版权,所以就没有考虑过其他的东东。不过唯一不足的地方就是需要安装(包括Win Zip和其Command Line Addon),而且需要让程序知道调用的WinZIP路径,配置起来不是很方便。

本次项目,考虑到程序的易配置性,决定采用另外别的方式进行压缩,找了找就找到了ICSharpCode的SharpZipLib组件,开源的,并且功能很强大:压缩、解压缩、加密等等一系列功能都有,而且调用起来也蛮方便的,于是决定采用该组件了。

同样,为了能够更好的为项目服务,也对该组件作了封装,调用更加简单。

using System;
using System.IO;
using System.Collections;

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

namespace BenQ.Modias.Utility
...{
    /**////<summary>
    ///******************************************************************
    ///**  Creator     : Venus Feng 
    ///**  Create Date : 2006-9-19 16:21
    ///**  Modifier    : 
    ///**  Modify Date : 
    ///**  Description : Use ICSharpZipLib to ZIP File
    ///** 
    ///** 
    ///**  Version No  : 1.0.0
    ///** 
    ///******************************************************************
    ///</summary>
    public class ZIPPER : IDisposable
    ...{
        private string m_FolderToZIP;
        private ArrayList m_FileNamesToZIP;
        private string m_FileNameZipped;
        
        private ZipOutputStream m_ZipStream = null;
        private Crc32 m_Crc;

        Begin for Public Properties#region Begin for Public Properties
        /**//// <summary>
        /// Folder Name to ZIP
        /// Like "C:Test"
        /// </summary>
        public  string FolderToZIP
        ...{
            get ...{ return m_FolderToZIP; }
            set ...{ m_FolderToZIP = value; }
        }

        /**//// <summary>
        /// File Name to ZIP
        /// Like "C:TestTest.txt"
        /// </summary>
        public  ArrayList FileNamesToZIP
        ...{
            get ...{ return m_FileNamesToZIP; }
            set ...{ m_FileNamesToZIP = value; }
        }

        /**//// <summary>
        /// Zipped File Name 
        /// Like "C:TestMyZipFile.ZIP"
        /// </summary>
        public  string FileNameZipped
        ...{
            get ...{ return m_FileNameZipped; }
            set ...{ m_FileNameZipped = value; }
        }
        #endregion

        /**//// <summary>
        /// The construct
        /// </summary>
        public ZIPPER()
        ...{
            this.m_FolderToZIP = "";
            this.m_FileNamesToZIP = new ArrayList();
            this.m_FileNameZipped = "";
        }

        ZipFolder#region ZipFolder
        /**//// <summary>
        /// Zip one folder : single level
        /// Before doing this event, you must set the Folder and the ZIP file name you want
        /// </summary>
        public void ZipFolder()
        ...{
            if (this.m_FolderToZIP.Trim().Length == 0)
            ...{
                throw new Exception("You must setup the folder name you want to zip!");
            }

            if(Directory.Exists(this.m_FolderToZIP) == false)
            ...{
                throw new Exception("The folder you input does not exist! Please check it!");
            }
            
            if (this.m_FileNameZipped.Trim().Length == 0)
            ...{
                throw new Exception("You must setup the zipped file name!");
            }
            
            string[] fileNames = Directory.GetFiles(this.m_FolderToZIP.Trim());

            if (fileNames.Length == 0)
            ...{
                throw new Exception("Can not find any file in this folder(" + this.m_FolderToZIP + ")!");
            }

            // Create the Zip File
            this.CreateZipFile(this.m_FileNameZipped);

            // Zip all files
            foreach(string file in fileNames)
            ...{
                this.ZipSingleFile(file);
            }

            // Close the Zip File
            this.CloseZipFile();
        }
        #endregion

        ZipFiles#region ZipFiles
        /**//// <summary>
        /// Zip files
        /// Before doing this event, you must set the Files name and the ZIP file name you want
        /// </summary>
        public void ZipFiles()
        ...{
            if (this.m_FileNamesToZIP.Count == 0)
            ...{
                throw new Exception("You must setup the files name you want to zip!");
            }

            foreach(object file in this.m_FileNamesToZIP)
            ...{
                if(File.Exists(((string)file).Trim()) == false)
                ...{
                    throw new Exception("The file(" + (string)file + ") you input does not exist! Please check it!");
                }
            }

            if (this.m_FileNameZipped.Trim().Length == 0)
            ...{
                throw new Exception("You must input the zipped file name!");
            }

            // Create the Zip File
            this.CreateZipFile(this.m_FileNameZipped);

            // Zip this File
            foreach(object file in this.m_FileNamesToZIP)
            ...{
                this.ZipSingleFile((string)file);
            }

            // Close the Zip File
            this.CloseZipFile();
        }
        #endregion

        CreateZipFile#region CreateZipFile
        /**//// <summary>
        /// Create Zip File by FileNameZipped
        /// </summary>
        /// <param name="fileNameZipped">zipped file name like "C:TestMyZipFile.ZIP"</param>
        private void CreateZipFile(string fileNameZipped)
        ...{
            this.m_Crc = new Crc32();
            this.m_ZipStream = new ZipOutputStream(File.Create(fileNameZipped));
            this.m_ZipStream.SetLevel(6); // 0 - store only to 9 - means best compression
        }
        #endregion

        CloseZipFile#region CloseZipFile
        /**//// <summary>
        /// Close the Zip file
        /// </summary>
        private void CloseZipFile()
        ...{
            this.m_ZipStream.Finish();
            this.m_ZipStream.Close();
            this.m_ZipStream = null;
        }
        #endregion

        ZipSingleFile#region ZipSingleFile
        /**//// <summary>
        /// Zip single file 
        /// </summary>
        /// <param name="fileName">file name like "C:TestTest.txt"</param>
        private void ZipSingleFile(string fileNameToZip)
        ...{
            // Open and read this file
            FileStream fso = File.OpenRead(fileNameToZip);

            // Read this file to Buffer
            byte[] buffer = new byte[fso.Length];
            fso.Read(buffer,0,buffer.Length);

            // Create a new ZipEntry
            ZipEntry zipEntry = new ZipEntry(fileNameToZip.Split('\')[fileNameToZip.Split('\').Length - 1]);
            
            zipEntry.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.
            zipEntry.Size = fso.Length;

            fso.Close();
            fso = null;

            // Using CRC to format the buffer
            this.m_Crc.Reset();
            this.m_Crc.Update(buffer);
            zipEntry.Crc = this.m_Crc.Value;

            // Add this ZipEntry to the ZipStream
            this.m_ZipStream.PutNextEntry(zipEntry);
            this.m_ZipStream.Write(buffer,0,buffer.Length);
        }
        #endregion

        IDisposable member#region IDisposable member

        /**//// <summary>
        /// Release all objects
        /// </summary>
        public void Dispose()
        ...{
            if(this.m_ZipStream != null)
            ...{
                this.m_ZipStream.Close();
                this.m_ZipStream = null;
            }
        }

        #endregion
    }
}


 

 

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!


























本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2009/07/08/1519502.html ,如需转载请自行联系原作者




相关文章
|
1月前
|
存储 C#
【C#】大批量判断文件是否存在的两种方法效率对比
【C#】大批量判断文件是否存在的两种方法效率对比
39 1
|
1月前
|
存储 C#
C#使用哈夫曼编码实现压缩与解压
C#使用哈夫曼编码实现压缩与解压
25 0
|
1月前
|
XML 存储 缓存
C#使用XML文件的详解及示例
C#使用XML文件的详解及示例
88 0
|
3月前
|
监控 安全 C#
使用C#如何监控选定文件夹中文件的变动情况?
使用C#如何监控选定文件夹中文件的变动情况?
117 19
|
3月前
|
编译器 C# Windows
C#基础:手动编译一个.cs源代码文件并生成.exe可执行文件
通过上述步骤,应该能够高效准确地编译C#源代码并生成相应的可执行文件。此外,这一过程强调了对命令行编译器的理解,这在调试和自动化编译流程中是非常重要的。
255 2
|
3月前
|
文字识别 C# Python
使用C#将几个Excel文件合并去重分类
使用C#将几个Excel文件合并去重分类
32 3
|
3月前
|
C# 图形学 数据安全/隐私保护
Unity数据加密☀️ 二、使用Rider将C#代码生成DLL文件
Unity数据加密☀️ 二、使用Rider将C#代码生成DLL文件
|
3月前
|
C#
C# 写日志文件
C# 写日志文件
44 0
|
5月前
|
C#
【C#】C#读写Excel文件
【C#】C#读写Excel文件
128 1
|
5月前
|
JavaScript 前端开发 C#
初识Unity——创建代码、场景以及五个常用面板(创建C#代码、打开代码文件、场景的创建、Project、Hierarchy、Inspector、Scene、Game )
初识Unity——创建代码、场景以及五个常用面板(创建C#代码、打开代码文件、场景的创建、Project、Hierarchy、Inspector、Scene、Game )
307 0