Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the output of a System.Diagnostics.Process?

I run ffmpeg like this:

System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = new System.Diagnostics.ProcessStartInfo(ffmpegPath, myParams); p.Start(); p.WaitForExit(); 

... but the problem is that the console with ffmpeg pops up and disappears right away, so I can't get any feedback. I don't even know if the process ran correctly.

So how can I either:

  • Tell the console to stay opened

  • Retrieve in the C# what the console displayed

like image 604
marcgg Avatar asked Sep 07 '09 18:09

marcgg


People also ask

What is System diagnostics process start?

Starts a process resource by specifying the name of an application and a set of command-line arguments, and associates the resource with a new Process component. public: static System::Diagnostics::Process ^ Start(System::String ^ fileName, System::String ^ arguments); C# Copy. public static System.Diagnostics.

What is stdout in C#?

Stdout means "Standard Output". This typically refers to the console.

What is process in C# example?

C# Process class provides Start method for launching an exe from code. The Process class is in the System. Diagnostics namespace that has methods to run a .exe file to see any document or a webpage. The Process class provides Start methods for launching another application in the C# Programming.

What is a process in VB net?

The Process component is a useful tool for starting, stopping, controlling, and monitoring applications. The System. Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters. Imports System.Diagnostics.


1 Answers

What you need to do is capture the Standard Output stream:

p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; // instead of p.WaitForExit(), do string q = ""; while ( ! p.HasExited ) {     q += p.StandardOutput.ReadToEnd(); } 

You may also need to do something similar with StandardError. You can then do what you wish with q.

It is a bit finicky, as I discovered in one of my questions

As Jon Skeet has pointed out, it is not smart performance-wise to use string concatenation like this; you should instead use a StringBuilder:

p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; // instead of p.WaitForExit(), do StringBuilder q = new StringBuilder(); while ( ! p.HasExited ) {     q.Append(p.StandardOutput.ReadToEnd()); } string r = q.ToString(); 
like image 143
Lucas Jones Avatar answered Sep 23 '22 01:09

Lucas Jones