private bool InstallUsePnPUtil(string fileName) { try { var startInfo = new ProcessStartInfo("pnputil", $"-i -a {fileName}") { Verb = "runas", CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; var outputBuilder = new OutputBuilder(); int exitCode = 0; using (var proc = Process.Start(startInfo)) { proc.OutputDataReceived += (s, e) => { outputBuilder.AppendOut(e.Data); }; proc.ErrorDataReceived += (s, e) => { outputBuilder.AppendError(e.Data); }; proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); exitCode = proc.ExitCode; proc.Dispose(); return(exitCode == 0); } } catch (Exception ex) { SLogger <OSImpl> .Warn("failed", ex); return(false); } }
/// <summary> /// 执行命令 /// </summary> /// <param name="fileName"></param> /// <param name="args"></param> /// <returns></returns> public ICommandResult Execute(string fileName, string args) { lock (_executingLock) { if (isDisposed) { throw new ObjectDisposedException(nameof(HestExecutor)); } //输出构造器 outputBuilder.Clear(); //记录开始时间 DateTime start = DateTime.Now; //开始进程 currentProcess = Process.Start(GetStartInfo(fileName, args)); //监听 currentProcess.OutputDataReceived += (s, e) => { outputBuilder.AppendOut(e.Data); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false)); }; currentProcess.ErrorDataReceived += (s, e) => { outputBuilder.AppendError(e.Data); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true)); }; currentProcess.BeginOutputReadLine(); currentProcess.BeginErrorReadLine(); //触发事件 CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args)); //等待进程结束 currentProcess.WaitForExit(); currentProcess.CancelErrorRead(); currentProcess.CancelOutputRead(); //记录结束时间 DateTime end = DateTime.Now; //构造结果对象 var result = new HestExecutorResult() { ExitCode = currentProcess.ExitCode, Output = outputBuilder.Result }; //触发结束事件 CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start)); //返回结果 return(result); }; }