user1158745
user1158745

Reputation: 2490

Redirecting STD error & STDOut

I am currently having issues redirecting both STDError and STDOutput. What I want to do is when there is an error to be printed to a rich text box along with normal output if no error is thrown.

The issue I am having is that if I add the line to redirect the SDT Error:

string error = process1.StandardError.ReadToEnd();
rchsdtOut.Text = error;

Then my normal STD Out doesn't redirect to the text fild, but if there is an error that is printed.

process1 = new System.Diagnostics.Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.RedirectStandardError = true;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.FileName = "java.exe ";

//String abc = txtSingleBar.Text.Replace("\\", "/");
toLoad = lstBarToLoad.Items[i].Text;

 process1.StartInfo.Arguments = "-Xmx512M -jar";
 process1.StartInfo.Arguments += toLoad;

Console.WriteLine(process1.StartInfo.Arguments);
 try
  {
    process1.Start();      
    process1.OutputDataReceived += (s, a) => myMethod(a);
    process1.BeginOutputReadLine();

    string error = process1.StandardError.ReadToEnd();
    rchsdtOut.Text = error;
 }

Method to write events to a text fild

private void myMethod(DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        Action action = () => rchsdtOut.Text += "\r\n" + e.Data.ToString();
        rchsdtOut.BeginInvoke(action, null);
        Console.WriteLine(e.Data.ToString());
    }

}//end of private

Bascally what I want is both to be redirected, SDTOut and SDTError if one should occur.

Any ideas?

Upvotes: 1

Views: 381

Answers (1)

qJake
qJake

Reputation: 17139

Why not just take this:

process1.OutputDataReceived += (s, a) => myMethod(a);
process1.BeginOutputReadLine();

and add this: (Don't forget to add myErrorMethod!)

process1.ErrorDataReceived += (s, a) => myErrorMethod(a);
process1.BeginErrorReadLine();

Then take out this:

string error = process1.StandardError.ReadToEnd();

and instead, do this (if you want to wait for it to end):

process1.WaitForExit();

Basically, you cannot mix synchronous and asynchronous output reads. You have to either use Begin_______ReadLine() or read the stream objects, but not both.

Upvotes: 2

Related Questions