当前位置: 开源爱好者 » 编程教程 » C#教程 » 正文

C#调用 WinRAR实现文件解压和压缩功能

C#解压文件,并调用Windows可已安装 的Winrar库文件,实现基于Winrar算法的文件压缩和解压操作实例:

private void button6_Click(object sender, EventArgs e)
{//解压缩文件
    var MySourceFile = "C:\\NW.arj";
    var MyDestinationFile = "C:\\Northwind.mdb";
    if (System.IO.File.Exists(MySourceFile) == false)
        return;
    byte[] MyBuffer = null;
    var MySourceStream = new System.IO.FileStream(MySourceFile, System.IO.FileMode.Open);
    var MyDecompressedStream = new System.IO.Compression.GZipStream(MySourceStream, System.IO.Compression.CompressionMode.Decompress, true);
    MyBuffer = new byte[4];
    var MyPosition = (int)MySourceStream.Length - 4;
    MySourceStream.Position = MyPosition;
    MySourceStream.Read(MyBuffer, 0, 4);
    MySourceStream.Position = 0;
    var MyLength = BitConverter.ToInt32(MyBuffer, 0);
    byte[] MyData = new byte[MyLength + 100];
    var MyOffset = 0;
    var MyTotal = 0;
    while (true)
    {
      int MyBytesRead = MyDecompressedStream.Read(MyData, MyOffset, 100);
      if (MyBytesRead == 0)
          break;
      MyOffset += MyBytesRead;
      MyTotal += MyBytesRead;
    }
    var MyDestinationStream = new System.IO.FileStream(MyDestinationFile, System.IO.FileMode.Create);
    MyDestinationStream.Write(MyData, 0, MyTotal);
    MyDestinationStream.Flush();
    MessageBox.Show("解压缩文件顺利完成!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    if (MySourceStream != null)
       MySourceStream.Close();
    if (MyDecompressedStream != null)
       MyDecompressedStream.Close();
    if (MyDestinationStream != null)
       MyDestinationStream.Close();            
}
private void button7_Click(object sender, EventArgs e)
{//使用WinRAR压缩文件
    var MyRar =@"C:\Program Files\WinRAR\WinRAR.exe";
    var MyInfo = " a    " + "C:\\CompressFile.arj " + "  " + "F:\\Northwind.mdb";
    var MyStartInfo = new System.Diagnostics.ProcessStartInfo();
    MyStartInfo.FileName = MyRar;
    MyStartInfo.Arguments = MyInfo;
    MyStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    var MyProcess = new System.Diagnostics.Process();
    MyProcess.StartInfo = MyStartInfo;
    MyProcess.Start();
    MessageBox.Show("执行压缩文件操作成功!", "信息提示", MessageBoxButtons.OK);                     
}
private void button8_Click(object sender, EventArgs e)
{//使用WinRAR解压缩文件
    var MyRar = @"C:\Program Files\WinRAR\WinRAR.exe";
    var  MyInfo = " X " + " C:\\CompressFile.arj " + " " + "C:\\";
    var  MyStartInfo = new System.Diagnostics.ProcessStartInfo();
    MyStartInfo.FileName = MyRar;
    MyStartInfo.Arguments = MyInfo;
    MyStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    var MyProcess = new System.Diagnostics.Process();
    MyProcess.StartInfo = MyStartInfo;
    MyProcess.Start();
    MessageBox.Show("执行解压文件操作成功!", "信息提示", MessageBoxButtons.OK);            
}

若使用本代码,请确保你的电脑中安装有WinRAR压缩软件。

CopyRight 2018© 开源爱好者 All Rights Reserved 豫ICP备16030607号 隐私声明 网站地图