C#使用ICSharpCode.SharpZipLib压缩文件

来源:互联网 发布:spss数据分析应用案例 编辑:程序博客网 时间:2024/05/01 00:53
一直以来都是采用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;

        
#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 = "";
        }


        
#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


        
#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


        
#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


        
#region CloseZipFile
        
/// <summary>
        
/// Close the Zip file
        
/// </summary>

        private void CloseZipFile()
        
{
            
this.m_ZipStream.Finish();
            
this.m_ZipStream.Close();
            
this.m_ZipStream = null;
        }

        
#endregion


        
#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


        
#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

    }

}

 

 *********************************************************************************************************************

另一小段:

通过引用一DLL(ICSharpCode.dll)可以实现所述功能。。。

一、压缩文件

using System;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Checksums;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Collections;

namespace wsUpFiles
{
 /// <summary>
 /// Common 的摘要说明。
 /// </summary>
 public class Common
 {
  public Common()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }

  /// <summary>
  /// 压缩文件
  /// </summary>
  /// <param name="sourceFileNames">压缩文件名称集合</param>
  /// <param name="destFileName">压缩后文件名称</param>
  /// <param name="password">密码</param>
  public static void zipFile(string path,string destFileName)
  {
   Crc32 crc = new Crc32();
   ZipOutputStream s = new ZipOutputStream(File.Create(destFileName));
   s.Password="";
   s.SetLevel(6); // 0 - store only to 9 - means best compression
   //定义
   System.IO.DirectoryInfo myDir = new DirectoryInfo(path);
   if(myDir.Exists == true)
   {
    System.IO.FileInfo[] myFileAry = myDir.GetFiles();
    
    //循环提取文件夹下每一个文件,提取信息,
    foreach (FileInfo objFiles in myFileAry)
    {
     FileStream fs = File.OpenRead(objFiles.FullName);
     byte[] buffer = new byte[fs.Length];
     fs.Read(buffer, 0, buffer.Length);
     ZipEntry entry = new ZipEntry(objFiles.FullName);
     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);           
    }   
    s.Finish();
    s.Close();
   }
  }
  
 }
}

要对压缩文件加密时,要s.Password = "aaa"; aaa为密码

二、解压文件

 /// <summary>
  /// 解压文件
  /// </summary>
  /// <param name="sourceFileName">被解压文件名称</param>
  /// <param name="destPath">解压后文件目录</param>
  /// <param name="password">密码</param>
  public static void unzipFile(string sourceFileName,string destPath,string fileType)
  {
   ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFileName));
   ZipEntry theEntry;
   ArrayList al=new ArrayList();

   while ((theEntry = s.GetNextEntry()) != null)
   {   
    string fileName=Path.GetFileName(theEntry.Name);
    if(fileName!="")
    {
     fileName=destPath+"//"+fileName;
     if(!Directory.Exists(destPath))
     {
      Directory.CreateDirectory(destPath);
     }
     FileStream streamWriter = File.Create(fileName);     
     int size = 2048;
     byte[] data = new byte[2048];
     s.Password="";
     while (true)
     {
      size = s.Read(data, 0, data.Length);
      if (size > 0)
      {
       streamWriter.Write(data, 0, size);
      }
      else
      {
       break;
      }
     }
     streamWriter.Close();
    }

   }
   s.Close();
   
  }

注意:程序的压缩过的文件,要通过系统上的工具解压出来的路径会相当多,因其在压缩时保留了原来的绝对路径,但压缩的文件中只包含所压缩的目标文件,当用程序解压出来的文件是相对的文件路径。