今天,项目上要用到带密码的RAR压缩包的下载和解压。尽管网上有很多源码,但感觉还是花了很多时间,而且看的有点晕了。不过,终于还是搞明白了。简单整理下,以供参考。
一,下载网络文件到本地
public void DownloadFile()
{
//网络文件全路径
string path = @"http://www.baidu.com/img/baidu_sylogo1.gif";
//文件名
string filename = path.Substring(path.LastIndexOf('/') + 1);
//本地临时文件夹
string fileDir = Environment.GetEnvironmentVariable("TEMP");
//目标文件全名
string fullname = fileDir + @"\" + filename;
try
{
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(path, fullname);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
二,解压缩带密码RAR
/// <summary>
/// WinRAR解压缩
/// </summary>
/// <param name="rarFile">RAR压缩包全路径</param>
/// <param name="unRarDir">解压目录文件夹</param>
public void unCompressRAR(string rarFile, string unRarDir)
{
//WinRAR软件路径
string winrarPath;
//WinRAR对应注册表
RegistryKey winrarKey;
//解压密码
string password="123456";
try
{
winrarKey=Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
winrarPath=winrarKey.GetValue("").ToString();
winrarKey.Close();
ProcessStartInfo startInfo=new ProcessStartInfo ();
startInfo.FileName=winrarPath;
//-p是密码命令,-y是对话框结果全为是命令
startInfo.Arguments="x -p"+password+" "+rarFile+" "+unRarDir+" -y";
startInfo.WindowStyle=ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory=rarFile;
Process uncompressProcess=new Process ();
uncompressProcess.StartInfo=startInfo;
uncompressProcess.Start();
uncompressProcess.WaitForExit();
uncompressProcess.Close();
}
catch(Exception e)
{
throw new Exception(e.Message);
}
}