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

Windows系统中C#调用WinRAR来压缩和解压缩文件的方法

程序员文章站 2022-11-23 22:49:56
过程说明都在注释里,我们直接来看代码: 压缩: using system; using system.collections.generic; us...

过程说明都在注释里,我们直接来看代码:
压缩:

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.io;

using icsharpcode.sharpziplib.zip;

using system.diagnostics;

public class winrar

{
  #region 压缩文件

  /// <summary>

  /// 压缩文件

  /// </summary>

  /// <param name="filespath">压缩文件及完整路径(d:\abc)</param>

  /// <param name="zipfilepath">压缩包所存完整路径(d:\a.zip或d:\a.rar)</param>

  public static void createzipfile(string filespath, string zipfilepath)

  {

    if (!directory.exists(filespath))

    {

      console.writeline("cannot find directory '{0}'", filespath);

      return;

    }

    try

    {

      string[] filenames = directory.getfiles(filespath);

      using (zipoutputstream s = new zipoutputstream(file.create(zipfilepath)))

      {

        s.setlevel(9); // 压缩级别 0-9

        //s.password = "123"; //zip压缩文件密码

        byte[] buffer = new byte[4096]; //缓冲区大小

        foreach (string file in filenames)

        {

          zipentry entry = new zipentry(path.getfilename(file));

          entry.datetime = datetime.now;

          s.putnextentry(entry);

          using (filestream fs = file.openread(file))

          {

            int sourcebytes;

            do

            {

              sourcebytes = fs.read(buffer, 0, buffer.length);

              s.write(buffer, 0, sourcebytes);

            } while (sourcebytes > 0);

          }

        }

        s.finish();

        s.close();

      }

    }

    catch (exception ex)

    {

      autocompare.errorlog.saveerror(ex, "压缩文件出错!");

    }

  }

  #endregion

  #region 解压文件

  /// <summary>

  /// 解压文件

  /// </summary>

  /// <param name="zipfilepath">解压文件及完整路径(d:\a.zip或d:\a.rar)</param>

  public static void unzipfile(string zipfilepath)

  {

    if (!file.exists(zipfilepath))

    {

      console.writeline("cannot find file '{0}'", zipfilepath);

      return;

    }

    using (zipinputstream s = new zipinputstream(file.openread(zipfilepath)))

    {

      zipentry theentry;

      while ((theentry = s.getnextentry()) != null)

      {

        console.writeline(theentry.name);

        string directoryname = path.getdirectoryname(theentry.name);

        string filename = path.getfilename(theentry.name);

        // create directory

        if (directoryname.length > 0)

        {

          directory.createdirectory(directoryname);

        }

        if (filename != string.empty)

        {

          using (filestream streamwriter = file.create(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;

              }

            }

          }

        }

      }

    }

  }

  #endregion


   string rarfile=@"c:\program files\winrar\winrar.exe";//winrar之所在的路径,这里找执行文件所在文件夹和"c:\program files\winrar\winrar.exe

 #region rar压缩文件(支持路径中含有空格)

 /// <summary>

  /// 压缩到.rar

  /// </summary>

  /// <param name="intputpath">输入目录</param>

  /// <param name="outputpath">输出目录</param>

  /// <param name="outputfilename">输出文件名</param>

 

  public static void compressrar(string intputpath, string outputpath, string outputfilename)

  {

    //rar 执行时的命令、参数

    string rarcmd;

    //启动进程的参数

    processstartinfo processstartinfo;

    //进程对象

    process process;

 //命令参数

 rarcmd = " a " + outputfilename + " " + intputpath + " -r -ep1";

 //rar路径

 string rarfile = system.windows.forms.application.startuppath + @"\rar.exe";

 if (outputpath.indexof(' ') > 0 || intputpath.indexof(' ') > 0)

 {

  rarcmd = " a " + outputfilename + " \"" + intputpath + "\" -r -ep1";

 }

 if (!file.exists(system.windows.forms.application.startuppath + @"\rar.exe"))

 { 

  rarfile=@"c:\program files\winrar\winrar.exe";

 }

    try

    {

      

      //判断输入目录是否存在

      if (!directory.exists(intputpath))

      {

        throw new argumentexception("compressrar'arge : inputpath isn't exsit.");

      }

      

      //创建启动进程的参数

      processstartinfo = new processstartinfo();

      //指定启动文件名

      processstartinfo.filename = @"c:\program files\winrar\winrar.exe";

      //指定启动该文件时的命令、参数

      processstartinfo.arguments = rarcmd;

      //指定启动窗口模式:隐藏

      processstartinfo.windowstyle = processwindowstyle.hidden;

      //指定压缩后到达路径

      processstartinfo.workingdirectory = outputpath;

      //创建进程对象

      process = new process();

      //指定进程对象启动信息对象

      process.startinfo = processstartinfo;

      //启动进程

      process.start();

      //指定进程自行退行为止

      process.waitforexit();

    }

    catch (exception ex)

    {

      throw ex;

    }

  }

 #endregion

 #region rar解压文件(支持路径中含有空格)

 /// <summary>

 /// 解压文件

 /// </summary>

 /// <param name="outputpath">解压到的路径</param>

 /// <param name="inputpath">压缩包所在路径(解压路径需存在)</param>

 /// <param name="inputfilename">压缩包名</param>

 /// <returns></returns>

 

 public static void decompressrar(string outputpath, string inputpath, string inputfilename)

 {

 //rar 执行时的命令、参数

 string rarcmd;

 //启动进程的参数

 processstartinfo processstartinfo;

 //进程对象

 process process;

 //rar路径

 string rarfile =system.windows.forms.application.startuppath + @"\rar.exe" ;

 //命令参数

 rarcmd = " e " + inputfilename + " " + outputpath + " -r -ep1";

 if (outputpath.indexof(' ') > 0 || inputpath.indexof(' ') > 0)

 {

  rarcmd = "x -inul -y -o+ -ep1 \"" + inputpath + "\\" + inputfilename + "\" \"" + outputpath+"\"";

 }

 if (!file.exists(system.windows.forms.application.startuppath + @"\rar.exe"))

 { 

  rarfile=@"c:\program files\winrar\winrar.exe";

 }

 try

 {

  //创建启动进程的参数

  processstartinfo = new processstartinfo();

  //指定启动文件名

  processstartinfo.filename = rarfile;

  //指定启动该文件时的命令、参数

  processstartinfo.arguments = rarcmd;

  //指定启动窗口模式:隐藏

  processstartinfo.windowstyle = processwindowstyle.hidden;

  //指定解压后到达路径(文件夹需要存在)

  processstartinfo.workingdirectory = inputpath;

  //创建进程对象

  process = new process();

  //指定进程对象启动信息对象

  process.startinfo = processstartinfo;

  //启动进程

  process.start();

  //指定进程自行退行为止

  process.waitforexit();

  //释放资源

  process.close();

 }

 catch (exception ex)

 {

  throw ex;

 }

 }

 #endregion

}

解压:

class usewinrar 
  { 
    private string rarexefile = null;//winrar.exe路径 
    private bool useable = false;//标志winrar是否可用 
 
    public usewinrar()//构造方法 
    { 
      rarexefile = getrarexe(); 
      useable = !string.isnullorempty(rarexefile);//如果winrar.exe路径不为空,说明可用 
    } 
 
    public static string getrarexe()//获取winrar所在磁盘路径 
    { 
      string rarexe = null; 
      registrykey regkey = registry.localmachine.opensubkey(@"software\microsoft\windows\currentversion\app paths\winrar.exe"); 
      if (regkey == null) 
      { 
        return null; 
      } 
      rarexe = regkey.getvalue("").tostring(); 
      regkey.close();//关闭注册表 
      return rarexe; 
    } 
 
    public bool exerarcmd(string cmd)//执行某个命令 
    { 
      if (!useable) 
      { 
        return false; 
      } 
      process process = new process();//新建一个过程 
      processstartinfo startinfo = new processstartinfo(rarexefile);//新建一个启动信息 
      startinfo.arguments = cmd;//设置启动信息的执行参数 
      //startinfo.workingdirectory = workdirectory;//设置启动信息的工作目录 
      startinfo.windowstyle = processwindowstyle.hidden;//设置程序后台运行 
      process.startinfo = startinfo;//设置过程的启动信息 
      process.start();//开始过程 
      return true; 
    } 
 
    public bool unzipall(string zipfile, string targetdirectory)//将指定压缩文件解压到指定目录 
    { 
      if (! file.exists(zipfile)) 
      { 
        return false; 
      } 
      string zipcmd = "x " + zipfile +" "+ targetdirectory + " -y -ibck";//后台解压压缩文件中全部文件到指定目录 
      exerarcmd(zipcmd);//执行解压操作 
      return true; 
    } 
 
    public bool unziptocurrentdirectory(string zipfile)//将压缩文件解压到当前目录 
    { 
      if (!file.exists(zipfile)) 
      { 
        return false; 
      } 
      fileinfo fileinfo = new fileinfo(zipfile); 
      return unzipall(zipfile, fileinfo.directoryname); 
    } 
  } 
  
main:
public static void main() 
    { 
      usewinrar rar = new usewinrar(); 
      string[] zipfiles = directory.getfiles(environment.currentdirectory, "*.zip");//获取所有zip文件路径 
      foreach (string zipfile in zipfiles) 
      { 
        rar.unziptocurrentdirectory(zipfile); 
      } 
    }