Reuse Process, capturing output

E

Elpoca

Hi:

I am trying to capture std output from a console application and
redirect it to a textbox. The code below works the first time the
process is started, but on subsequent starts it fails to capture the
output (the process definitely runs every time). What am I doing
wrong?

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
process1.Start();
process1.BeginOutputReadLine();
process1.WaitForExit();
process1.CancelOutputRead(); // This doesn't help...
}

private void process1_OutputDataReceived(object sender,
DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
textBox1.AppendText(e.Data);
}
}
}
}

In InitializeComponent:

//
// process1
//
this.process1.StartInfo.CreateNoWindow = true;
this.process1.StartInfo.Domain = "";
this.process1.StartInfo.ErrorDialog = true;
this.process1.StartInfo.FileName =
"writetexttoconsole.exe";
this.process1.StartInfo.LoadUserProfile = false;
this.process1.StartInfo.Password = null;
this.process1.StartInfo.RedirectStandardOutput = true;
this.process1.StartInfo.StandardErrorEncoding = null;
this.process1.StartInfo.StandardOutputEncoding = null;
this.process1.StartInfo.UserName = "";
this.process1.StartInfo.UseShellExecute = false;
this.process1.SynchronizingObject = this;
this.process1.OutputDataReceived += new
System.Diagnostics.DataReceivedEventHandler(this.process1_OutputDataReceived);

Thanks,
Elpoca
 
P

Peter Duniho

Hi:

I am trying to capture std output from a console application and
redirect it to a textbox. The code below works the first time the
process is started, but on subsequent starts it fails to capture the
output (the process definitely runs every time). What am I doing
wrong?

I'm surprised the process runs on subsequent tries.

Maybe I just don't know the Process class well enough, but I'd create a
new instance of Process for each time you want to run the process.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top