分享

关于C#对文件的压缩和解压缩的问题

 悟静 2011-12-04

项目中用到压缩和解压的功能,在网上查查看,有如下几种,整理一下,供参考
: 引用第三方的插件实现
在引用中添加ICSharpCode.SharpZipLib.dll文件

可从www./Opensource/SharpZipLib/Download.aspx获得

需要添加以下引用

using ICSharpCode.SharpZipLib.Checksums;

using ICSharpCode.SharpZipLib.Zip;

using ICSharpCode.SharpZipLib.GZip;


对文件压缩的方法如下:

 // 对目标文件夹进行压缩,将压缩结果保存为指定文件

 //FilePath存放的是目标文件夹下要压缩的文件BakPath 压缩后文件存放的路径

public class ZipClass
 {
  
           public ArrayList Zip(string FilePath, string BakPath)

  {
   // 新建一个list数组,用于存储压缩后的文件的名字
   ArrayList list = new ArrayList();
   try
   {

    string[] filenames = Directory.GetFiles(FilePath);
    
    list.Add(filenames);
    Crc32 crc = new Crc32();//新建Checksums的Crc32类对象

    ZipOutputStream ZipStream = new ZipOutputStream(File.Create(BakPath));

    foreach (string file in filenames)

    {

     //打开要压缩的文件

     FileStream fs = File.OpenRead(file);

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

     //获取压缩文件的相对路径

     string files = file.Substring(file.LastIndexOf("\\"));
     ZipEntry entry = new ZipEntry(files);

     entry.DateTime = DateTime.Now;

     entry.Size = fs.Length;

     fs.Close();

     crc.Reset();

     crc.Update(buffer);

     entry.Crc = crc.Value;

     ZipStream.PutNextEntry(entry);

     ZipStream.Write(buffer, 0, buffer.Length);

    }

    ZipStream.Finish();

    ZipStream.Close();
    return list;
   }
   catch (Exception ee)
   {
    throw ee;            
   }

  }

 

在解压缩类中添加如下引用

using ICSharpCode.SharpZipLib.Zip;


对文件的解压缩的方法如下:

public void UnZip(string[] args)

{

     ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));

ZipEntry theEntry;

     while ((theEntry = s.GetNextEntry()) != null)

     {

string directoryName = Path.GetDirectoryName(args[1]);

string fileName = Path.GetFileName(theEntry.Name);

         //生成解压目录

          Directory.CreateDirectory(directoryName);

if (fileName != String.Empty)

          {

            //解压文件到指定的目录

             FileStream streamWriter = File.Create(args[1] + 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();

        }
. Net 2.0中的自带的GZipStream


 
在压缩和解压缩的时候只要添加如下引用

 using System.IO.Compression;
对文件压缩方法如下:

public void CompressFile(string sourceFile, string destinationFile)

{

if (File.Exists(sourceFile) == false) //判断文件是否存在

       throw new FileNotFoundException();

//创建文件流和字节数组

byte[] buffer = null;

FileStream sourceStream = null;

FileStream destinationStream = null;

GZipStream compressedStream = null;

   try

{

     sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);

     buffer = new byte[sourceStream.Length];

//把文件流存放到字节数组中

      int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);

if (checkCounter != buffer.Length)

        {

             throw new ApplicationException();

         }

destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write);

//创建GzipStream实例,写入压缩的文件流

        compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true);

         compressedStream.Write(buffer, 0, buffer.Length);

      }

     catch (ApplicationException ex)

      {

          MessageBox.Show(ex.Message, "压缩文件时发生错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);

       }

       finally

      {

           // Make sure we allways close all streams

           if (sourceStream != null)

               {     sourceStream.Close();}

           if (compressedStream != null)

                {    compressedStream.Close();}

           if (destinationStream != null)

                {    destinationStream.Close();}

       }

}


解压缩方法如下:

  public void DecompressFile(string sourceFile, string destinationFile)

  {

       if (File.Exists(sourceFile) == false)

             throw new FileNotFoundException();

        FileStream sourceStream = null;

        FileStream destinationStream = null;

        GZipStream decompressedStream = null;

        byte[] quartetBuffer = null;

        try

        {

         sourceStream = new FileStream(sourceFile, FileMode.Open);

         decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true);

         quartetBuffer = new byte[4];

int position = (int)sourceStream.Length - 4;

sourceStream.Position = position;

sourceStream.Read(quartetBuffer, 0, 4);

sourceStream.Position = 0;

int checkLength = BitConverter.ToInt32(quartetBuffer, 0);

byte[] buffer = new byte[checkLength + 100];

int offset = 0;

int total = 0;

          // 从字节数组中读取压缩数据

         while (true)

           {

                    int bytesRead = decompressedStream.Read(buffer, offset, 100);

                    if (bytesRead == 0) break;

                    offset += bytesRead;

                    total += bytesRead;

             }

            destinationStream = new FileStream(destinationFile, FileMode.Create);

            destinationStream.Write(buffer, 0, total);

             destinationStream.Flush();

          }

          catch (ApplicationException ex)

          {

              MessageBox.Show(ex.Message, "解压文件时发生错误:", MessageBoxButtons.OK, MessageBoxIcon.Error);

          }

          finally

          {              

                if (sourceStream != null)

                   { sourceStream.Close();}

                if (decompressedStream != null)

                   { decompressedStream.Close();}

                if (destinationStream != null)

                  {  destinationStream.Close();}

         }

       }

比较:

 引用 SharpZipLib的方法通用性比较强,能压缩和对别的解压文件进行解压;

 GzipStream类对文件进行压缩和解压比较方便,但是其只能对自己的压缩文件进行解压,对常见的压缩格式不支持
粗略的总结了一下,有错误的地方还望多多指出. ^_^

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约