/// <summary> /// Runs a process. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="arguments">The arguments.</param> /// <param name="workingDirectory">The working directory.</param> public void StartProcess(string fileName, string arguments, string workingDirectory) { // Create the process start info. var processStartInfo = new ProcessStartInfo(fileName) { Arguments = arguments, // Set the options. UseShellExecute = false, ErrorDialog = false, CreateNoWindow = true, // Specify redirection. RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true }; if (!string.IsNullOrEmpty(workingDirectory)) { processStartInfo.WorkingDirectory = workingDirectory; } // Create the process. Process = new Process { EnableRaisingEvents = true, StartInfo = processStartInfo }; Process.Exited += CurrentProcess_Exited; // Start the process. try { Process.Start(); } catch (Exception e) { // Trace the exception. Trace.WriteLine("Failed to start process " + fileName + " with arguments '" + arguments + "'"); Trace.WriteLine(e.ToString()); return; } // Store name and arguments. ProcessFileName = fileName; ProcessArguments = arguments; // Create the readers and writers. InputWriter = Process.StandardInput; OutputReader = TextReader.Synchronized(Process.StandardOutput); ErrorReader = TextReader.Synchronized(Process.StandardError); // Run the workers that read output and error. OutputWorker.RunWorkerAsync(); ErrorWorker.RunWorkerAsync(); }
/// <summary> /// Handles the Exited event of the currentProcess control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> void CurrentProcess_Exited(object sender, EventArgs e) { // Fire process exited. if (Process is not null) { FireProcessExitEvent(Process.ExitCode); } // Disable the threads. OutputWorker.CancelAsync(); ErrorWorker.CancelAsync(); InputWriter = null; OutputReader = null; ErrorReader = null; Process = null; ProcessFileName = null; ProcessArguments = null; }
/// <summary> /// Handles the DoWork event of the errorWorker control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DoWorkEventArgs" /> instance containing the event data.</param> void ErrorWorker_DoWork(object sender, DoWorkEventArgs e) { while (!ErrorWorker.CancellationPending && ErrorReader is not null) { // Any lines to read? int count; var buffer = new char[1024]; do { var builder = new StringBuilder(); count = ErrorReader.Read(buffer, 0, 1024); builder.Append(buffer, 0, count); ErrorWorker.ReportProgress(0, builder.ToString()); } while (count > 0); System.Threading.Thread.Sleep(200); } }