2012-02-02 105 views
0

所以我在做的是调用java.exe并用一些参数调用jar文件。如果everyting没有问题并且该命令有效,那么这些参数将打印到richtext框中。重定向标准错误

我遇到的问题是命令不正确。因此,在一次实例中,假设用户键入传入txtPassword的错误密码。 Stanadard没有被重定向。如果我在Dos控制台中运行完全相同的命令,则会显示消息“错误:身份验证失败”。我如何将该错误重定向到富文本框?我认为重定向stdout会做到这一点,但显然不是。

任何帮助将apprecaited。请参阅下面的代码。

//Declare and instantiate a new process component. 
       System.Diagnostics.Process process1; 
       process1 = new System.Diagnostics.Process(); 
       process1.StartInfo.UseShellExecute = false; 
       process1.StartInfo.RedirectStandardOutput = true; 
       process1.StartInfo.CreateNoWindow = true; 

       process1.StartInfo.FileName = "java.exe "; 

       toLoad = lstBarToLoad.Items[i].Text; 

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

       Console.WriteLine(process1.StartInfo.Arguments); 

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

    //myMthod 
    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 
+0

你看过'Process'上的成员吗?您可能会注意到errorDataReceived看起来像OutputDataReceived的等效版本... http://msdn.microsoft.com/en-us/library/system.diagnostics.process.errordatareceived.aspx – Chris 2012-02-02 14:16:59

回答

2

除了使用

process1.StartInfo.RedirectStandardOutput = true; 

你还需要使用

process1.StartInfo.RedirectStandardError = true; 

Gets or sets a value that indicates whether the error output of an application is written to the Process.StandardError stream

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

然后,您可以读出错误,并用它做的你请:

string error = process1.StandardError.ReadToEnd(); 
+0

所以我将RedirectStandarError添加到了我的代码中但仍然没有... – user1158745 2012-02-02 14:22:43

+0

您是否正在阅读错误? 'string error = process1.StandardError.ReadToEnd();' – 2012-02-02 14:26:34

+0

所以这个问题,现在是STDOUT没有被重定向。 – user1158745 2012-02-02 16:26:34