Process.StandardError Proprietà

Definizione

Ottiene un flusso usato per leggere l'output di errore dell'applicazione.

public:
 property System::IO::StreamReader ^ StandardError { System::IO::StreamReader ^ get(); };
public System.IO.StreamReader StandardError { get; }
[System.ComponentModel.Browsable(false)]
public System.IO.StreamReader StandardError { get; }
member this.StandardError : System.IO.StreamReader
[<System.ComponentModel.Browsable(false)>]
member this.StandardError : System.IO.StreamReader
Public ReadOnly Property StandardError As StreamReader

Valore della proprietà

Oggetto StreamReader che può essere usato per leggere il flusso di errore standard dell'applicazione.

Attributi

Eccezioni

Il flusso StandardError non è stato definito per il reindirizzamento; assicurarsi che RedirectStandardError sia impostato su true e che UseShellExecute sia impostato su false.

-oppure-

Il flusso StandardError è stato aperto per operazioni di lettura asincrona con BeginErrorReadLine().

Esempio

Nell'esempio seguente viene usato il comando insieme a un argomento fornito dall'utente per eseguire il net use mapping di una risorsa di rete. Legge quindi il flusso di errori standard del comando net e lo scrive nella 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

Commenti

Quando un Process testo scrive nel flusso di errore standard, questo testo viene normalmente visualizzato nella console. Reindirizzando il flusso, è possibile modificare o eliminare l'output StandardError degli errori di un processo. Ad esempio, è possibile filtrare il testo, formattarlo in modo diverso o scrivere l'output nella console e in un file di log designato.

Nota

Per usare StandardError, è necessario impostare ProcessStartInfo.UseShellExecute su falsee è necessario impostare ProcessStartInfo.RedirectStandardError su true. In caso contrario, la lettura dal flusso genera un'eccezione StandardError .

Il flusso reindirizzato StandardError può essere letto in modo sincrono o asincrono. Metodi come Read, ReadLineed ReadToEnd eseguire operazioni di lettura sincrone nel flusso di output degli errori del processo. Queste operazioni di lettura sincrone non vengono completate fino a quando le scritture StandardError associate Process al flusso non vengono completate o chiude il flusso.

Al contrario, BeginErrorReadLine avvia operazioni di lettura asincrone nel StandardError flusso. Questo metodo abilita un gestore eventi designato per l'output del flusso e restituisce immediatamente al chiamante, che può eseguire altre operazioni mentre l'output del flusso viene indirizzato al gestore eventi.

Le operazioni di lettura sincrone introducono una dipendenza tra la lettura del chiamante dal StandardError flusso e il processo figlio che scrive in tale flusso. Queste dipendenze possono causare condizioni di deadlock. Quando il chiamante legge dal flusso reindirizzato di un processo figlio, dipende dal figlio. Il chiamante attende l'operazione di lettura fino a quando il figlio scrive nel flusso o chiude il flusso. Quando il processo figlio scrive dati sufficienti per riempire il flusso reindirizzato, dipende dall'elemento padre. Il processo figlio attende l'operazione di scrittura successiva fino a quando l'elemento padre legge dal flusso completo o chiude il flusso. La condizione deadlock risulta quando il chiamante e il processo figlio attendono l'uno dall'altro per completare un'operazione e nessuno può procedere. È possibile evitare deadlock valutando le dipendenze tra il chiamante e il processo figlio.

Gli ultimi due esempi di questa sezione usano il Start metodo per avviare un eseguibile denominato Write500Lines.exe. L'esempio seguente contiene il codice sorgente.

using System;
using System.IO;

public class Example3
{
   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.

Nell'esempio seguente viene illustrato come leggere da un flusso di errori reindirizzato e attendere l'uscita dal processo figlio. Evita una condizione di deadlock chiamando p.StandardError.ReadToEnd prima p.WaitForExitdi . Una condizione di deadlock può causare se il processo padre chiama p.WaitForExit prima p.StandardError.ReadToEnd e il processo figlio scrive testo sufficiente per riempire il flusso reindirizzato. Il processo padre attende in modo indefinito l'uscita dal processo figlio. Il processo figlio attende in modo indefinito che l'elemento padre venga letto dal flusso completo StandardError .

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.

Si verifica un problema simile quando si legge tutto il testo sia dall'output standard che dai flussi di errore standard. Nell'esempio seguente viene eseguita un'operazione di lettura in entrambi i flussi. Evita la condizione di deadlock eseguendo operazioni di lettura asincrone nel StandardError flusso. Una condizione di deadlock risulta se il processo padre chiama p.StandardOutput.ReadToEnd seguito da p.StandardError.ReadToEnd e il processo figlio scrive testo sufficiente per riempire il flusso di errori. Il processo padre attende in modo indefinito il processo figlio per chiudere StandardOutput il flusso. Il processo figlio attende in modo indefinito che l'elemento padre venga letto dal flusso completo StandardError .

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.

È possibile usare operazioni di lettura asincrone per evitare queste dipendenze e il potenziale di deadlock. In alternativa, è possibile evitare la condizione di deadlock creando due thread e leggendo l'output di ogni flusso in un thread separato.

Nota

Non è possibile combinare operazioni di lettura asincrone e sincrone in un flusso reindirizzato. Una volta aperto il flusso reindirizzato di un Process oggetto in modalità asincrona o sincrona, tutte le operazioni di lettura aggiuntive su tale flusso devono trovarsi nella stessa modalità. Ad esempio, non seguire BeginErrorReadLine con una chiamata al ReadLineStandardError flusso o viceversa. Tuttavia, è possibile leggere due flussi diversi in modalità diverse. Ad esempio, è possibile chiamare e quindi chiamare BeginOutputReadLineReadLine il StandardError flusso.

Si applica a

Vedi anche