C#利用WinRAR實現(xiàn)壓縮和解壓縮
當(dāng)前位置:點晴教程→知識管理交流
→『 技術(shù)文檔交流 』
using
System; using
Microsoft.Win32; using
System.Diagnostics; using
System.IO;
namespace MSCL { ///
<summary> ///
壓縮解壓類 ///
</summary> public class ZipHelper {
/// <summary>
/// 利用 WinRAR 進行壓縮
/// </summary> /// <param
name="path">將要被壓縮的文件夾(絕對路徑)</param>
/// <param
name="rarPath">壓縮后的 .rar 的存放目錄(絕對路徑)</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; //注冊表鍵
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)上點右鍵->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(); //無限期等待進程 winrar.exe 退出 if
(process.HasExited) { flag = true; } process.Close();
}
catch (Exception e)
{ throw e;
}
return flag;
}
/// <summary>
/// 利用 WinRAR 進行解壓縮
/// </summary>
/// <param
name="path">文件解壓路徑(絕對)</param>
/// <param
name="rarPath">將要解壓縮的 .rar 文件的存放目錄(絕對路徑)</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)上點右鍵->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;
} } } 該文章在 2021/5/31 8:29:50 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |