/// <summary> /// /// </summary> /// <param name="h"></param> /// <param name="res"></param> public void Merge(ConsoleApplicationHandler h, ConsoleApplicationResult res) { Timeouted = Timeouted || res.Timeouted; Exception = Exception ?? res.Exception; if (0 == State) { State = res.IsOK?0:res.State; Output += "Command: " + h.ExePath + " " + h.Arguments + "\r\n" + res.Output + res.Error; } if (0 != State) { Error += "Command: " + h.ExePath + " " + h.Arguments + "\r\n" + res.Error + res.Output; } }
private static ConsoleApplicationResult DoDeleteCommand(ProcessStartInfo startinfo, ConsoleApplicationResult result) { var fullpath = Path.Combine(startinfo.WorkingDirectory, startinfo.Arguments.Replace("\"", "").Trim()); var mask = Path.GetFileName(fullpath); var dir = Path.GetDirectoryName(fullpath); try { if (Directory.Exists(dir)) { var files = Directory.GetFiles(dir, mask); foreach (var file in files) { try { File.Delete(file); } catch { try { Thread.Sleep(10); File.Delete(file); } catch { } } } } result.State = 0; } catch (Exception ex) { result.State = -1; result.Exception = ex; } return(result); }
/// <summary> /// /// </summary> /// <returns></returns> public ConsoleApplicationResult RunSync() { if (IsStub) { var res = new ConsoleApplicationResult(); if (null != OnStub) { OnStub.Invoke(this, new ConsoleApplicationResult()); } return(res); } Interlocked.Increment(ref Calls); var result = new ConsoleApplicationResult(); var startinfo = PrepareStrartInfo(); result.StartInfo = startinfo; if (ExePath == "del") { return(DoDeleteCommand(startinfo, result)); } var process = new Process { StartInfo = startinfo }; try{ var output = new StringBuilder(); var error = new StringBuilder(); process.OutputDataReceived += (s, e) => { output.AppendLine(e.Data); if (null != Listener) { Listener.EmitOutput(e.Data); CheckMessage(process); } }; process.ErrorDataReceived += (s, e) => { error.AppendLine(e.Data); if (null != Listener) { Listener.EmitOutput(e.Data); CheckMessage(process); } }; try{ var wellFinish = false; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (null != SendLines && 0 != SendLines.Length) { foreach (var sendLine in SendLines) { process.StandardInput.WriteLine(sendLine); } } CheckMessage(process); if (0 != Timeout) { wellFinish = process.WaitForExit(Timeout); result.Timeouted = !wellFinish; } else { process.WaitForExit(); wellFinish = true; } if (!wellFinish) { if (!process.HasExited) { process.Kill(); } } result.State = process.ExitCode; result.Output = output.ToString(); result.Error = error.ToString(); } catch (Exception ex) { result.Exception = ex; } return(result); } finally{ if (!process.HasExited) { process.Kill(); } } }