Running an executable file with parameters and output using C#

It is really nice to call an executable file as if it was called in command prompt. I will explain this issue step by step.

1)First we need to create a ProcessStartInfo object:
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("simple_console.exe");

2)Then we set some properties of processStartInfo before calling the actual exe file:
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;

3)One of the properties takes parameters as a string:
psi.Arguments = "param1 param2";

4)It is time to create a System.Diagnostics.Process object.
System.Diagnostics.Process listFiles;
listFiles = System.Diagnostics.Process.Start(psi);

5)If we want to wait executable program to be ended, we need to use HasExited of process object.
while (!listFiles.HasExited) { }

6)If output of the program is important, it can also be taken as a string.
System.IO.StreamReader myOutput = listFiles.StandardOutput;
string output = myOutput.ReadToEnd();

No comments:

Post a Comment