C#使用WinRar命令进行压缩和解压缩操作的实现方法


本文实例讲述了C#使用WinRar命令进行压缩和解压缩操作的实现方法。分享给大家供大家参考,具体如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.IO;
public partial class Zip : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
  }
  //压缩文件
  protected void Button1_Click(object sender, EventArgs e)
  {
    ProcessStartInfo startinfo = new ProcessStartInfo(); ;
    Process process = new Process();
    string rarName = "1.rar"; //压缩后文件名
    string path = @"C:\images"; //待压缩打包文件夹
    string rarPath = @"C:\zip"; //压缩后存放文件夹
    string rarexe = @"c:\Program Files\WinRAR\WinRAR.exe"; //WinRAR安装位置
    try
    {
      //压缩命令,相当于在要压缩的文件夹(path)上点右键->WinRAR->添加到压缩文件->输入压缩文件名(rarName)
      string cmd = string.Format("a {0} {1} -r", rarName, path);
      startinfo.FileName = rarexe;
      startinfo.Arguments = cmd;             //设置命令参数
      startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口
      startinfo.WorkingDirectory = rarPath;
      process.StartInfo = startinfo;
      process.Start();
      process.WaitForExit(); //无限期等待进程 winrar.exe 退出
      if (process.HasExited)
      {
        MSCL.JsHelper.Alert("压缩成功!", Page);
      }
    }
    catch (Exception ex)
    {
      MSCL.JsHelper.Alert(ex.Message, Page);
    }
    finally
    {
      process.Dispose();
      process.Close();
    }
  }
  //解压文件
  protected void Button2_Click(object sender, EventArgs e)
  {
    ProcessStartInfo startinfo = new ProcessStartInfo(); ;
    Process process = new Process();
    string rarName = "1.rar"; //将要解压缩的 .rar 文件名(包括后缀)
    string path = @"C:\images1"; //文件解压路径(绝对)
    string rarPath = @"C:\zip"; //将要解压缩的 .rar 文件的存放目录(绝对路径)
    string rarexe = @"c:\Program Files\WinRAR\WinRAR.exe"; //WinRAR安装位置
    try
    {
      //解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹
      string cmd = string.Format("x {0} {1} -y", rarName, path);
      startinfo.FileName = rarexe;
      startinfo.Arguments = cmd;             //设置命令参数
      startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口
      startinfo.WorkingDirectory = rarPath;
      process.StartInfo = startinfo;
      process.Start();
      process.WaitForExit(); //无限期等待进程 winrar.exe 退出
      if (process.HasExited)
      {
        MSCL.JsHelper.Alert("解压缩成功!", Page);
      }
    }
    catch (Exception ex)
    {
      MSCL.JsHelper.Alert(ex.Message, Page);
    }
    finally
    {
      process.Dispose();
      process.Close();
    }
  }
}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#常见控件用法教程》、《WinForm控件用法总结》、《C#数据结构与算法教程》、《C#面向对象程序设计入门教程》及《C#程序设计之线程使用技巧总结》

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3