ProcessStartInfo.RedirectStandardError 屬性

定義

取得或設定值,表示應用程式的錯誤輸出是否寫入至 StandardError 資料流。Gets or sets a value that indicates whether the error output of an application is written to the StandardError stream.

public:
 property bool RedirectStandardError { bool get(); void set(bool value); };
public bool RedirectStandardError { get; set; }
member this.RedirectStandardError : bool with get, set
Public Property RedirectStandardError As Boolean

屬性值

如果錯誤輸出應該寫入至 StandardError,則為 true,否則為falsetrue if error output should be written to StandardError; otherwise, false. 預設為 falseThe default is false.

範例

下列範例會使用 net use 命令搭配使用者提供的引數來對應網路資源。The following example uses the net use command together with a user-supplied argument to map a network resource. 然後,它會讀取 net 命令的標準錯誤資料流程,並將它寫入主控台。It then reads the standard error stream of the net command and writes it to console.

Process^ myProcess = gcnew Process;
ProcessStartInfo^ myProcessStartInfo = gcnew ProcessStartInfo( "net ",String::Concat( "use ", args[ 0 ] ) );

myProcessStartInfo->UseShellExecute = false;
myProcessStartInfo->RedirectStandardError = true;
myProcess->StartInfo = myProcessStartInfo;
myProcess->Start();

StreamReader^ myStreamReader = myProcess->StandardError;
// Read the standard error of net.exe and write it on to console.
Console::WriteLine( myStreamReader->ReadLine() );
myProcess->Close();
using (Process myProcess = new Process())
{
    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("net ", "use " + args[0]);

    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardError = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();

    StreamReader myStreamReader = myProcess.StandardError;
    // Read the standard error of net.exe and write it on to console.
    Console.WriteLine(myStreamReader.ReadLine());
}
Using myProcess As New Process()
    Dim myProcessStartInfo As New ProcessStartInfo("net ", "use " + args(0))

    myProcessStartInfo.UseShellExecute = False
    myProcessStartInfo.RedirectStandardError = True
    myProcess.StartInfo = myProcessStartInfo
    myProcess.Start()

    Dim myStreamReader As StreamReader = myProcess.StandardError
    ' Read the standard error of net.exe and write it on to console.
    Console.WriteLine(myStreamReader.ReadLine())
End Using

備註

Process 將文字寫入其標準錯誤資料流程時,該文字通常會顯示在主控台上。When a Process writes text to its standard error stream, that text is typically displayed on the console. 藉由將 StandardError 資料流程重新導向,您可以操作或隱藏進程的錯誤輸出。By redirecting the StandardError stream, you can manipulate or suppress the error 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.

注意

如果您想要將 RedirectStandardError 設定為 true,您必須將 UseShellExecute 設定為 falseYou must set UseShellExecute to false if you want to set RedirectStandardError to true. 否則,從 StandardError 資料流程讀取時,會擲回例外狀況。Otherwise, reading from the StandardError stream throws an exception.

重新導向的 StandardError 串流可以透過同步或非同步方式讀取。The redirected StandardError stream can be read synchronously or asynchronously. ReadReadLineReadToEnd 等方法會在進程的錯誤輸出資料流程上執行同步讀取作業。Methods such as Read, ReadLine and ReadToEnd perform synchronous read operations on the error output stream of the process. 這些同步讀取作業在相關聯的 Process 寫入其 StandardError 資料流程或關閉資料流程之前,都不會完成。These synchronous read operations do not complete until the associated Process writes to its StandardError stream, or closes the stream.

相反地,BeginErrorReadLine 會在 StandardError 資料流程上啟動非同步讀取作業。In contrast, BeginErrorReadLine starts asynchronous read operations on the StandardError stream. 這個方法會針對資料流程輸出啟用指定的事件處理常式,並立即返回呼叫端,以便在資料流程輸出導向至事件處理常式時執行其他工作。This method enables a designated event handler for the stream output and immediately returns to the caller, which can perform other work while the stream output is directed to the event handler.

注意

處理非同步輸出的應用程式應該呼叫 Process.WaitForExit 方法,以確保輸出緩衝區已排清。The application that is processing the asynchronous output should call the Process.WaitForExit method to ensure that the output buffer has been flushed.

同步讀取作業會引進呼叫端讀取 StandardError 資料流程和寫入該資料流程的子進程之間的相依性。Synchronous read operations introduce a dependency between the caller reading from the StandardError stream and the child process writing to that stream. 這些相依性可能會導致鎖死狀況。These dependencies can cause deadlock conditions. 當呼叫端從子進程的重新導向資料流程讀取時,它會相依于子系。When the caller reads from the redirected stream of a child process, it is dependent on the child. 呼叫端會等待讀取作業,直到子系寫入資料流程或關閉資料流程為止。The caller waits for the read operation until the child writes to the stream or closes the stream. 當子進程寫入足夠的資料以填滿其重新導向的資料流程時,它會相依于父系。When the child process writes enough data to fill its redirected stream, it is dependent on the parent. 子進程會等待下一個寫入作業,直到父系讀取完整資料流程或關閉資料流程為止。The child process waits for the next write operation until the parent reads from the full stream or closes the stream. 當呼叫端和子進程等候彼此完成作業時,就會產生鎖死條件,而且兩者都不能繼續。The deadlock condition results when the caller and child process wait for each other to complete an operation, and neither can continue. 您可以藉由評估呼叫端和子進程之間的相依性來避免鎖死。You can avoid deadlocks by evaluating dependencies between the caller and child process.

本節中的最後兩個範例會使用 Start 方法來啟動名為Write500Lines的可執行檔。The last two examples in this section use the Start method to launch an executable named Write500Lines.exe. 下列範例包含其原始程式碼。The following example contains its source code.

using System;
using System.IO;

public class Example
{
   public static void Main()
   {
      for (int ctr = 0; ctr < 500; ctr++)
         Console.WriteLine($"Line {ctr + 1} of 500 written: {ctr + 1/500.0:P2}");

      Console.Error.WriteLine("\nSuccessfully wrote 500 lines.\n");
   }
}
// The example displays the following output:
//      The last 50 characters in the output stream are:
//      ' 49,800.20%
//      Line 500 of 500 written: 49,900.20%
//'
//
//      Error stream: Successfully wrote 500 lines.
Imports System.IO

Public Module Example
   Public Sub Main()
      For ctr As Integer = 0 To 499
         Console.WriteLine($"Line {ctr + 1} of 500 written: {ctr + 1/500.0:P2}")
      Next

      Console.Error.WriteLine($"{vbCrLf}Successfully wrote 500 lines.{vbCrLf}")
   End Sub
End Module
' The example displays the following output:
'      The last 50 characters in the output stream are:
'      ' 49,800.20%
'      Line 500 of 500 written: 49,900.20%
'
'
'      Error stream: Successfully wrote 500 lines.

下列範例顯示如何從重新導向的錯誤資料流程讀取,並等候子進程結束。The following example shows how to read from a redirected error stream and wait for the child process to exit. 它會在 p.WaitForExit 之前呼叫 p.StandardError.ReadToEnd,以避免發生鎖死狀況。It avoids a deadlock condition by calling p.StandardError.ReadToEnd before p.WaitForExit. 如果父進程在 p.StandardError.ReadToEnd 之前呼叫 p.WaitForExit,而子進程寫入足夠的文字來填滿重新導向的資料流程,則會產生鎖死狀況。A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. 父進程會無限期地等候子進程結束。The parent process would wait indefinitely for the child process to exit. 子進程會無限期地等候父系讀取完整的 StandardError 串流。The child process would wait indefinitely for the parent to read from the full StandardError stream.

using System;
using System.Diagnostics;

public class Example
{
   public static void Main()
   {
      var p = new Process();  
      p.StartInfo.UseShellExecute = false;  
      p.StartInfo.RedirectStandardError = true;  
      p.StartInfo.FileName = "Write500Lines.exe";  
      p.Start();  

      // To avoid deadlocks, always read the output stream first and then wait.  
      string output = p.StandardError.ReadToEnd();  
      p.WaitForExit();

      Console.WriteLine($"\nError stream: {output}");
   }
}
// The end of the output produced by the example includes the following:
//      Error stream:
//      Successfully wrote 500 lines.
Imports System.Diagnostics

Public Module Example
    Public Sub Main()
        Dim p As New Process()
        p.StartInfo.UseShellExecute = False  
        p.StartInfo.RedirectStandardError = True  
        p.StartInfo.FileName = "Write500Lines.exe"  
        p.Start() 

        ' To avoid deadlocks, always read the output stream first and then wait.  
        Dim output As String = p.StandardError.ReadToEnd()  
        p.WaitForExit()

        Console.WriteLine($"{vbCrLf}Error stream: {output}")
    End Sub
End Module
' The end of the output produced by the example includes the following:
'      Error stream:
'      Successfully wrote 500 lines.

當您從標準輸出和標準錯誤資料流程讀取所有文字時,會發生類似的問題。There is a similar issue when you read all text from both the standard output and standard error streams. 例如, C#下列程式碼會在兩個數據流上執行讀取作業。The following C# code, for example, performs a read operation on both streams. 它會在 StandardError 資料流程上執行非同步讀取作業,以避免鎖死狀況。It avoids the deadlock condition by performing asynchronous read operations on the StandardError stream. 如果父進程呼叫 p.StandardOutput.ReadToEnd 後接 p.StandardError.ReadToEnd,而子進程寫入足夠的文字來填滿其錯誤資料流程,則會產生鎖死狀況。A deadlock condition results if the parent process calls p.StandardOutput.ReadToEnd followed by p.StandardError.ReadToEnd and the child process writes enough text to fill its error stream. 父進程會無限期地等候子進程關閉其 StandardOutput 資料流程。The parent process would wait indefinitely for the child process to close its StandardOutput stream. 子進程會無限期地等候父系讀取完整的 StandardError 串流。The child process would wait indefinitely for the parent to read from the full StandardError stream.

using System;
using System.Diagnostics;

public class Example
{
   public static void Main()
   {
      var p = new Process();  
      p.StartInfo.UseShellExecute = false;  
      p.StartInfo.RedirectStandardOutput = true;  
      string eOut = null;
      p.StartInfo.RedirectStandardError = true;
      p.ErrorDataReceived += new DataReceivedEventHandler((sender, e) => 
                                 { eOut += e.Data; });
      p.StartInfo.FileName = "Write500Lines.exe";  
      p.Start();  

      // To avoid deadlocks, use an asynchronous read operation on at least one of the streams.  
      p.BeginErrorReadLine();
      string output = p.StandardOutput.ReadToEnd();  
      p.WaitForExit();

      Console.WriteLine($"The last 50 characters in the output stream are:\n'{output.Substring(output.Length - 50)}'");
      Console.WriteLine($"\nError stream: {eOut}");
   }
}
// The example displays the following output:
//      The last 50 characters in the output stream are:
//      ' 49,800.20%
//      Line 500 of 500 written: 49,900.20%
//      '
//
//      Error stream: Successfully wrote 500 lines.

Imports System.Diagnostics

Public Module Example
   Public Sub Main()
      Dim p As New Process()  
      p.StartInfo.UseShellExecute = False  
      p.StartInfo.RedirectStandardOutput = True  
      Dim eOut As String = Nothing
      p.StartInfo.RedirectStandardError = True
      AddHandler p.ErrorDataReceived, Sub(sender, e) eOut += e.Data 
      p.StartInfo.FileName = "Write500Lines.exe"  
      p.Start()  

      ' To avoid deadlocks, use an asynchronous read operation on at least one of the streams.  
      p.BeginErrorReadLine()
      Dim output As String = p.StandardOutput.ReadToEnd()  
      p.WaitForExit()

      Console.WriteLine($"The last 50 characters in the output stream are:{vbCrLf}'{output.Substring(output.Length - 50)}'")
      Console.WriteLine($"{vbCrLf}Error stream: {eOut}")
   End Sub
End Module
' The example displays the following output:
'      The last 50 characters in the output stream are:
'      ' 49,800.20%
'      Line 500 of 500 written: 49,900.20%
'      '
'
'      Error stream: Successfully wrote 500 lines.

您可以使用非同步讀取作業來避免這些相依性和其鎖死的潛能。You can use asynchronous read operations to avoid these dependencies and their deadlock potential. 或者,您可以建立兩個執行緒,並在個別的執行緒上讀取每個資料流程的輸出,以避免發生鎖死狀況。Alternately, you can avoid the deadlock condition by creating two threads and reading the output of each stream on a separate thread.

適用於

另請參閱