Capturing an c# executable output from another C#

2019-01-28 09:35发布

问题:

I am executing a C# program i.e a .exe from another C# program. but the .exe has some Console.WriteLine() in its program. I want to get the standard output into my C# program.

for example,

Consider a C# executable i.e 1.exe and there is another Program 2.cs.

I am calling from 2.cs 1.exe. Now there is some output that the console is displaying from 1. exe. But I want the ouput in my program 2.cs. for displaying information to user.

Is it possible? Please help

Thanks Sai sindhu

回答1:

You can use ProcessStartInfo.RedirectStandardOutput Property

Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();    

Console.WriteLine(compiler.StandardOutput.ReadToEnd());

compiler.WaitForExit();

http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx



回答2:

You have to redirect the standard output stream, have a look at the MSDN for more information.

When a Process writes text to its standard stream, that text is normally displayed on the console. By redirecting the StandardOutput stream, you can manipulate or suppress the output of a process. For example, you can filter the text, format it differently, or write the output to both the console and a designated log file.