1、封装
/// <summary> /// 调用Winrar.exe进行压缩文件 /// </summary> /// <param name="sourcePath">需要压缩文件路径</param> /// <param name="rarPath">压缩文件路径</param> /// <param name="isDeleteFile">压缩成功是否删除源文件</param> /// <param name="errMsg">压缩失败异常原因</param> /// <returns></returns> public static bool GetRAR(string sourcePath, string rarPath, bool isDeleteFile, out string errMsg) { errMsg = string.Empty; System.Diagnostics.Process winRarPro = new System.Diagnostics.Process(); try { //通过Regedit(注册表)找到WinRar文件 var registryKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); if (registryKey == null) { errMsg = $"未安装WinRar软件"; return false; } //获取winRar路径 string winRarPath = registryKey.GetValue("")?.ToString(); //关闭注册表 registryKey.Close(); winRarPro.StartInfo.FileName = winRarPath; //是否创建一个线程 winRarPro.StartInfo.CreateNoWindow = true; if (!System.IO.File.Exists(sourcePath)) { errMsg = $"需要压缩的文件不存在;{sourcePath}"; return false; } winRarPro.StartInfo.Arguments = " a -ep " + rarPath + " " + sourcePath; winRarPro.Start(); //等待压缩时间(单位毫秒) winRarPro.WaitForExit(50000); //删除临时文件 if (isDeleteFile == true) { System.IO.File.Delete(sourcePath); } return true; } catch (Exception ex) { errMsg = $"压缩失败;{ex.Message};{ex.ToString()}"; return false; } finally { winRarPro?.Close(); winRarPro?.Dispose(); } }
调用测试
string msg = string.Empty; string sourceFilePath = "D:\\日志\\1.xls"; string compressedFilePathName = "D:\\日志\\1.rar"; GetRAR(sourceFilePath, compressedFilePathName, false, out msg);
标签:return,string,C#,压缩文件,sourcePath,winRarPro,Winrar,errMsg From: https://www.cnblogs.com/yuanshuo/p/16751529.html