C#利用WinRAR實(shí)現(xiàn)壓縮和解壓縮
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
using System; using Microsoft.Win32; using System.Diagnostics; using System.IO; namespace MSCL { /// <summary> /// 壓縮解壓類 /// </summary> public class ZipHelper { /// <summary> /// 利用 WinRAR 進(jìn)行壓縮 /// </summary> /// <param name="path">將要被壓縮的文件夾(絕對(duì)路徑)</param> /// <param name="rarPath">壓縮后的 .rar 的存放目錄(絕對(duì)路徑)</param> /// <param name="rarName">壓縮文件的名稱(包括后綴)</param> /// <returns>true 或 false。壓縮成功返回 true,反之,false。</returns> public bool RAR(string path, string rarPath, string rarName) { bool flag = false; string rarexe; //WinRAR.exe 的完整路徑 RegistryKey regkey; //注冊(cè)表鍵 Object regvalue; //鍵值 string cmd; //WinRAR 命令參數(shù) ProcessStartInfo startinfo; Process process; try { regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); regvalue = regkey.GetValue("WinRAR"); // 鍵值為 "d:\Program Files\WinRAR\WinRAR.exe" "%1" rarexe = regvalue.ToString(); regkey.Close(); rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe Directory.CreateDirectory(path); //壓縮命令,相當(dāng)于在要壓縮的文件夾(path)上點(diǎn)右鍵->WinRAR->添加到壓縮文件->輸入壓縮文件名(rarName) cmd = string.Format("a {0} {1} -r", rarName, path); startinfo = new ProcessStartInfo(); startinfo.FileName = rarexe; startinfo.Arguments = cmd; //設(shè)置命令參數(shù) startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隱藏 WinRAR 窗口 startinfo.WorkingDirectory = rarPath; process = new Process(); process.StartInfo = startinfo; process.Start(); process.WaitForExit(); //無(wú)限期等待進(jìn)程 winrar.exe 退出 if (process.HasExited) { flag = true; } process.Close(); } catch (Exception e) { throw e; } return flag; } /// <summary> /// 利用 WinRAR 進(jìn)行解壓縮 /// </summary> /// <param name="path">文件解壓路徑(絕對(duì))</param> /// <param name="rarPath">將要解壓縮的 .rar 文件的存放目錄(絕對(duì)路徑)</param> /// <param name="rarName">將要解壓縮的 .rar 文件名(包括后綴)</param> /// <returns>true 或 false。解壓縮成功返回 true,反之,false。</returns> public bool UnRAR(string path, string rarPath, string rarName) { bool flag = false; string rarexe; RegistryKey regkey; Object regvalue; string cmd; ProcessStartInfo startinfo; Process process; try { regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command"); regvalue = regkey.GetValue(""); rarexe = regvalue.ToString(); regkey.Close(); rarexe = rarexe.Substring(1, rarexe.Length - 7); Directory.CreateDirectory(path); //解壓縮命令,相當(dāng)于在要壓縮文件(rarName)上點(diǎn)右鍵->WinRAR->解壓到當(dāng)前文件夾 cmd = string.Format("x {0} {1} -y", rarName, path); startinfo = new ProcessStartInfo(); startinfo.FileName = rarexe; startinfo.Arguments = cmd; startinfo.WindowStyle = ProcessWindowStyle.Hidden; startinfo.WorkingDirectory = rarPath;
process = new Process(); process.StartInfo = startinfo; process.Start(); process.WaitForExit(); if (process.HasExited) { flag = true; } process.Close(); } catch (Exception e) { throw e; } return flag; } } } 該文章在 2018/1/31 12:10:00 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |