程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Windows體系中C#挪用WinRAR來緊縮息爭緊縮文件的辦法

Windows體系中C#挪用WinRAR來緊縮息爭緊縮文件的辦法

編輯:C#入門知識

Windows體系中C#挪用WinRAR來緊縮息爭緊縮文件的辦法。本站提示廣大學習愛好者:(Windows體系中C#挪用WinRAR來緊縮息爭緊縮文件的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Windows體系中C#挪用WinRAR來緊縮息爭緊縮文件的辦法正文


進程解釋都在正文裡,我們直接來看代碼:
緊縮:

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); 
      } 
    } 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved