ProcessStartInfo.RedirectStandardOutput Eigenschap

Definitie

Hiermee wordt een waarde opgehaald of ingesteld die aangeeft of de tekstuele uitvoer van een toepassing naar de StandardOutput stream wordt geschreven.

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

Waarde van eigenschap

trueals uitvoer moet worden weggeschreven naar StandardOutput; anders . false De standaardwaarde is false.

Voorbeelden

// Run "csc.exe /r:System.dll /out:sample.exe stdstr.cs". UseShellExecute is false because we're specifying
// an executable directly and in this case depending on it being in a PATH folder. By setting
// RedirectStandardOutput to true, the output of csc.exe is directed to the Process.StandardOutput stream
// which is then displayed in this console window directly.
using (Process compiler = new Process())
{
    compiler.StartInfo.FileName = "csc.exe";
    compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
    compiler.StartInfo.UseShellExecute = false;
    compiler.StartInfo.RedirectStandardOutput = true;
    compiler.Start();

    Console.WriteLine(compiler.StandardOutput.ReadToEnd());

    compiler.WaitForExit();
}
' Run "vbc.exe /reference:Microsoft.VisualBasic.dll /out:sample.exe stdstr.vb". UseShellExecute is False 
' because we're specifying an executable directly and in this case depending on it being in a PATH folder. 
' By setting RedirectStandardOutput to True, the output of csc.exe is directed to the Process.StandardOutput 
' stream which is then displayed in this console window directly.    
Using compiler As New Process()
    compiler.StartInfo.FileName = "vbc.exe"
    compiler.StartInfo.Arguments = "/reference:Microsoft.VisualBasic.dll /out:sample.exe stdstr.vb"
    compiler.StartInfo.UseShellExecute = False
    compiler.StartInfo.RedirectStandardOutput = True
    compiler.Start()

    Console.WriteLine(compiler.StandardOutput.ReadToEnd())

    compiler.WaitForExit()
End Using

Opmerkingen

Wanneer een Process tekst naar de standaardstroom schrijft, wordt die tekst meestal weergegeven op de console. RedirectStandardOutput Door de stroom om te true leidenStandardOutput, kunt u de uitvoer van een proces manipuleren of onderdrukken. U kunt bijvoorbeeld de tekst filteren, anders opmaken of de uitvoer naar zowel de console als een aangewezen logboekbestand schrijven.

Note

U moet instellen op false als u wilt instellen UseShellExecuteRedirectStandardOutput op true. Anders genereert het lezen vanuit de StandardOutput stream een uitzondering.

De omgeleide StandardOutput stream kan synchroon of asynchroon worden gelezen. Methoden zoals Read, ReadLineen ReadToEnd voeren synchrone leesbewerkingen uit op de uitvoerstroom van het proces. Deze synchrone leesbewerkingen worden pas voltooid als de bijbehorende Process schrijfbewerkingen naar StandardOutput de stream zijn voltooid of de stream worden gesloten.

Start daarentegen BeginOutputReadLine asynchrone leesbewerkingen op de StandardOutput stream. Met deze methode kunt u een aangewezen gebeurtenis-handler (zie OutputDataReceived) voor de stroomuitvoer inschakelen en onmiddellijk terugkeren naar de aanroeper, die ander werk kan uitvoeren terwijl de stroomuitvoer wordt omgeleid naar de gebeurtenis-handler.

Note

De toepassing die de asynchrone uitvoer verwerkt, moet de WaitForExit methode aanroepen om ervoor te zorgen dat de uitvoerbuffer is leeggemaakt.

Synchrone leesbewerkingen introduceren een afhankelijkheid tussen de aanroeper die vanuit de StandardOutput stream leest en het onderliggende proces dat naar die stroom wordt geschreven. Deze afhankelijkheden kunnen impassevoorwaarden veroorzaken. Wanneer de beller leest vanuit de omgeleide stroom van een onderliggend proces, is deze afhankelijk van het onderliggende proces. De beller wacht op de leesbewerking totdat het kind naar de stream schrijft of de stream sluit. Wanneer het onderliggende proces voldoende gegevens schrijft om de omgeleide stream te vullen, is het afhankelijk van het bovenliggende proces. Het onderliggende proces wacht op de volgende schrijfbewerking totdat het bovenliggende item uit de volledige stream leest of de stream sluit. De impassevoorwaarde treedt op wanneer het aanroeper- en onderliggende proces wacht tot elkaar een bewerking heeft voltooid en geen van beide kan worden voortgezet. U kunt impasses voorkomen door afhankelijkheden tussen de aanroeper en het onderliggende proces te evalueren.

De laatste twee voorbeelden in deze sectie gebruiken de methode om een uitvoerbaar bestand met de Start naam Write500Lines.exete starten. Het volgende voorbeeld bevat de broncode.

using System;

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:
//      Line 1 of 500 written: 0,20%
//      Line 2 of 500 written: 0,40%
//      Line 3 of 500 written: 0,60%
//      ...
//      Line 498 of 500 written: 99,60%
//      Line 499 of 500 written: 99,80%
//      Line 500 of 500 written: 100,00%
//
//      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:
'      Line 1 of 500 written 0,20%
'      Line 2 of 500 written: 0,40%
'      Line 3 of 500 written: 0,60%
'      ...
'      Line 498 of 500 written: 99,60%
'      Line 499 of 500 written: 99,80%
'      Line 500 of 500 written: 100,00%
'
'      Successfully wrote 500 lines.

In het volgende voorbeeld ziet u hoe u kunt lezen uit een omgeleide stream en wacht tot het onderliggende proces is afgesloten. In het voorbeeld wordt een impassevoorwaarde vermeden door eerder p.WaitForExitaan te roepenp.StandardOutput.ReadToEnd. Een impassevoorwaarde kan resulteren als het bovenliggende proces eerder p.StandardOutput.ReadToEnd aanroept p.WaitForExit en het onderliggende proces voldoende tekst schrijft om de omgeleide stream te vullen. Het bovenliggende proces wacht voor onbepaalde tijd totdat het onderliggende proces is afgesloten. Het onderliggende proces wacht voor onbepaalde tijd totdat het bovenliggende item uit de volledige StandardOutput stream wordt gelezen.

using System;
using System.Diagnostics;

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

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

        Console.WriteLine($"The last 50 characters in the output stream are:\n'{output.Substring(output.Length - 50)}'");
    }
}
// The example displays the following output:
//      Successfully wrote 500 lines.
//
//      The last 50 characters in the output stream are:
//      'ritten: 99,80%
//      Line 500 of 500 written: 100,00%
//      '
Imports System.Diagnostics'

Public Module Example
   Public Sub Main()
      Dim p As New Process()
      p.StartInfo.UseShellExecute = False  
      p.StartInfo.RedirectStandardOutput = 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.StandardOutput.ReadToEnd()  
      p.WaitForExit()

      Console.WriteLine($"The last 50 characters in the output stream are:\n'{output.Substring(output.Length - 50)}'")
   End Sub
End Module
' The example displays the following output:
'      Successfully wrote 500 lines.
'
'      The last 50 characters in the output stream are:
'      'ritten: 99,80%
'      Line 500 of 500 written: 100,00%
'      '

Er is een vergelijkbaar probleem wanneer u alle tekst uit zowel de standaarduitvoer als de standaardfoutstromen leest. In het volgende voorbeeld wordt een leesbewerking uitgevoerd op beide streams. Het voorkomt de impassevoorwaarde door asynchrone leesbewerkingen uit te voeren op de StandardError stream. Een impassevoorwaarde resulteert als de bovenliggende procesaanroepen p.StandardOutput.ReadToEnd gevolgd door p.StandardError.ReadToEnd en het onderliggende proces voldoende tekst schrijft om de foutstroom te vullen. Het bovenliggende proces wacht voor onbepaalde tijd totdat het onderliggende proces de StandardOutput stream sluit. Het onderliggende proces wacht voor onbepaalde tijd totdat het bovenliggende item uit de volledige StandardError stream wordt gelezen.

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:
//      'ritten: 99,80%
//      Line 500 of 500 written: 100,00%
//      '
//
//      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:
'      'ritten: 99,80%
'      Line 500 of 500 written: 100,00%
'      '
'
'      Error stream: Successfully wrote 500 lines.

U kunt asynchrone leesbewerkingen gebruiken om deze afhankelijkheden en hun impassepotentieel te voorkomen. U kunt ook de impassevoorwaarde voorkomen door twee threads te maken en de uitvoer van elke stream op een afzonderlijke thread te lezen.

Van toepassing op

Zie ook