欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现的文件压缩和解压缩类

程序员文章站 2023-12-13 10:17:40
本文实例讲述了c#实现的文件压缩和解压缩类。分享给大家供大家参考。具体分析如下: 这个c#代码包含了几个类,封装了文件压缩和解压缩常用的方法,包括直接通过代码进行压缩,也...

本文实例讲述了c#实现的文件压缩和解压缩类。分享给大家供大家参考。具体分析如下:

这个c#代码包含了几个类,封装了文件压缩和解压缩常用的方法,包括直接通过代码进行压缩,也有调用winrar对文件进行压缩的

using system;
using system.io;
using system.diagnostics;
using microsoft.win32;
using icsharpcode.sharpziplib.checksums;
using icsharpcode.sharpziplib.zip;
///压缩、解压缩类
namespace dotnet.utilities
{
  public class sharpzip
  {
    public sharpzip()
    { }
    /// <summary>
    /// 压缩
    /// </summary> 
    /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
    /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
    public static void packfiles(string filename, string directory)
    {
      try
      {
        fastzip fz = new fastzip();
        fz.createemptydirectories = true;
        fz.createzip(filename, directory, true, "");
        fz = null;
      }
      catch (exception)
      {
        throw;
      }
    }
    /// <summary>
    /// 解压缩
    /// </summary>
    /// <param name="file">待解压文件名(包含物理路径)</param>
    /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
    public static bool unpackfiles(string file, string dir)
    {
      try
      {
        if (!directory.exists(dir))
        {
          directory.createdirectory(dir);
        }
        zipinputstream s = new zipinputstream(file.openread(file));
        zipentry theentry;
        while ((theentry = s.getnextentry()) != null)
        {
          string directoryname = path.getdirectoryname(theentry.name);
          string filename = path.getfilename(theentry.name);
          if (directoryname != string.empty)
          {
            directory.createdirectory(dir + directoryname);
          }
          if (filename != string.empty)
          {
            filestream streamwriter = file.create(dir + 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();
        return true;
      }
      catch (exception)
      {
        throw;
      }
    }
  }
  public class classzip
  {
    #region 私有方法
    /// <summary>
    /// 递归压缩文件夹方法
    /// </summary>
    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;
    }
    /// <summary>
    /// 压缩目录
    /// </summary>
    /// <param name="foldertozip">待压缩的文件夹,全路径格式</param>
    /// <param name="zipedfile">压缩后的文件名,全路径格式</param>
    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;
    }
    /// <summary>
    /// 压缩文件
    /// </summary>
    /// <param name="filetozip">要进行压缩的文件名</param>
    /// <param name="zipedfile">压缩后生成的压缩文件名</param>
    private static bool zipfile(string filetozip, string zipedfile, int level)
    {
      if (!file.exists(filetozip))
      {
        throw new system.io.filenotfoundexception("指定要压缩的文件: " + filetozip + " 不存在!");
      }
      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;
    }
    #endregion
    /// <summary>
    /// 压缩
    /// </summary>
    /// <param name="filetozip">待压缩的文件目录</param>
    /// <param name="zipedfile">生成的目标文件</param>
    /// <param name="level">6</param>
    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;
      }
    }
    /// <summary>
    /// 解压
    /// </summary>
    /// <param name="filetoupzip">待解压的文件</param>
    /// <param name="zipedfolder">解压目标存放目录</param>
    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 (s != null)
        {
          s.close();
          s = null;
        }
        gc.collect();
        gc.collect(1);
      }
    }
  }
  public class ziphelper
  {
    #region 私有变量
    string the_rar;
    registrykey the_reg;
    object the_obj;
    string the_info;
    processstartinfo the_startinfo;
    process the_process;
    #endregion
    /// <summary>
    /// 压缩
    /// </summary>
    /// <param name="zipname">要解压的文件名</param>
    /// <param name="zippath">要压缩的文件目录</param>
    /// <param name="dirpath">初始目录</param>
    public void enzip(string zipname, string zippath, string dirpath)
    {
      try
      {
        the_reg = registry.classesroot.opensubkey(@"applications\winrar.exe\shell\open\command");
        the_obj = the_reg.getvalue("");
        the_rar = the_obj.tostring();
        the_reg.close();
        the_rar = the_rar.substring(1, the_rar.length - 7);
        the_info = " a  " + zipname + " " + zippath;
        the_startinfo = new processstartinfo();
        the_startinfo.filename = the_rar;
        the_startinfo.arguments = the_info;
        the_startinfo.windowstyle = processwindowstyle.hidden;
        the_startinfo.workingdirectory = dirpath;
        the_process = new process();
        the_process.startinfo = the_startinfo;
        the_process.start();
      }
      catch (exception ex)
      {
        throw new exception(ex.message);
      }
    }
    /// <summary>
    /// 解压缩
    /// </summary>
    /// <param name="zipname">要解压的文件名</param>
    /// <param name="zippath">要解压的文件路径</param>
    public void dezip(string zipname, string zippath)
    {
      try
      {
        the_reg = registry.classesroot.opensubkey(@"applications\winrar.exe\shell\open\command");
        the_obj = the_reg.getvalue("");
        the_rar = the_obj.tostring();
        the_reg.close();
        the_rar = the_rar.substring(1, the_rar.length - 7);
        the_info = " x " + zipname + " " + zippath;
        the_startinfo = new processstartinfo();
        the_startinfo.filename = the_rar;
        the_startinfo.arguments = the_info;
        the_startinfo.windowstyle = processwindowstyle.hidden;
        the_process = new process();
        the_process.startinfo = the_startinfo;
        the_process.start();
      }
      catch (exception ex)
      {
        throw new exception(ex.message);
      }
    }
  }
}

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: