Read external console app window
I am calling an external command line app that continously spits out information into the console window. I'd like to read the information and pass it into my code in order to report progress.
But... I never get any values back at all. If I use sr.ReadToEnd(), it gets stuck until the app closes and just an empty string comes back. What do I need to do to read the text in the command line window of the external app correctly?
Here is my code for the test, doesn't have to be threaded, the stream comes back empty no matter what I seem 开发者_JAVA技巧to do:
private void runApp(string args, string app)
{
ProcessStartInfo pInfo = new ProcessStartInfo(app, args);
pInfo.CreateNoWindow = true;
pInfo.RedirectStandardOutput = true;
pInfo.UseShellExecute = false;
Thread t = new Thread(getProgress);
t.Start();
p = Process.Start(pInfo);
p.WaitForExit();
p.Close();
}
private void getProgress()
{
StreamReader sr = p.StandardOutput;
//Get's stuck here until the app closes, nothing is ever outputted
string output = sr.ReadLine();
//Just for testing, debugging here
while (true)
{
Console.WriteLine(output);
System.Threading.Thread.Sleep(1000);
}
sr.Close();
}
I'm thinking that the thread is started before the process and somehow you are deadlocking. Check out http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx
I see this subject is asked again and again every few days... see my answer here:
Running a c++ console app inside a C# console app
精彩评论