ProcessStartInfo.RedirectStandardOutput Properti

Definisi

Mendapatkan atau menetapkan nilai yang menunjukkan apakah output tekstual aplikasi ditulis ke StandardOutput aliran.

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

Nilai Properti

true jika output harus ditulis ke StandardOutput; jika tidak, false. Default adalah false.

Contoh

// Run "cl.exe /cld stdstr.cpp /link /out:sample.exe". 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 cl.exe is directed to the Process.StandardOutput stream
// which is then displayed in this console window directly.    
Process^ compiler = gcnew Process;
compiler->StartInfo->FileName = "cl.exe";
compiler->StartInfo->Arguments = "/clr stdstr.cpp /link /out:sample.exe";
compiler->StartInfo->UseShellExecute = false;
compiler->StartInfo->RedirectStandardOutput = true;
compiler->Start();

Console::WriteLine( compiler->StandardOutput->ReadToEnd() );

compiler->WaitForExit();
// 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

Keterangan

Process Saat menulis teks ke aliran standarnya, teks tersebut biasanya ditampilkan di konsol. Dengan mengatur RedirectStandardOutput ke true untuk mengalihkan StandardOutput aliran, Anda dapat memanipulasi atau menekan output proses. Misalnya, Anda dapat memfilter teks, memformatnya secara berbeda, atau menulis output ke konsol dan file log yang ditunjuk.

Catatan

Anda harus mengatur UseShellExecute ke false jika Anda ingin mengatur RedirectStandardOutput ke true. Jika tidak, membaca dari StandardOutput aliran akan melemparkan pengecualian.

Aliran yang dialihkan StandardOutput dapat dibaca secara sinkron atau asinkron. Metode seperti Read, ReadLine, dan ReadToEnd melakukan operasi baca sinkron pada aliran output proses. Operasi baca sinkron ini tidak selesai sampai penulisan terkait Process ke alirannya StandardOutput , atau menutup aliran.

Sebaliknya, BeginOutputReadLine memulai operasi baca asinkron pada StandardOutput aliran. Metode ini memungkinkan penanganan aktivitas yang ditunjuk (lihat OutputDataReceived) untuk output aliran dan segera kembali ke pemanggil, yang dapat melakukan pekerjaan lain saat output aliran diarahkan ke penanganan aktivitas.

Catatan

Aplikasi yang memproses output asinkron harus memanggil WaitForExit metode untuk memastikan bahwa buffer output telah dibersihkan.

Operasi baca sinkron memperkenalkan dependensi antara pembacaan pemanggil dari StandardOutput aliran dan penulisan proses anak ke aliran tersebut. Dependensi ini dapat menyebabkan kondisi kebuntuan. Ketika pemanggil membaca dari aliran yang dialihkan dari proses anak, itu tergantung pada anak. Penelepon menunggu operasi baca hingga anak menulis ke aliran atau menutup aliran. Ketika proses anak menulis data yang cukup untuk mengisi aliran yang dialihkan, itu tergantung pada induknya. Proses anak menunggu operasi tulis berikutnya hingga induk membaca dari aliran penuh atau menutup aliran. Kondisi kebuntuan menghasilkan ketika pemanggil dan proses anak menunggu satu sama lain untuk menyelesaikan operasi, dan tidak dapat dilanjutkan. Anda dapat menghindari kebuntuan dengan mengevaluasi dependensi antara pemanggil dan proses anak.

Dua contoh terakhir di bagian ini menggunakan Start metode untuk meluncurkan executable bernama Write500Lines.exe. Contoh berikut berisi kode sumbernya.

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.

Contoh berikut menunjukkan cara membaca dari aliran yang dialihkan dan menunggu proses anak keluar. Contohnya menghindari kondisi kebuntuan dengan memanggil p.StandardOutput.ReadToEnd sebelum p.WaitForExit. Kondisi kebuntuan dapat mengakibatkan proses induk memanggil p.WaitForExit sebelumnya p.StandardOutput.ReadToEnd dan proses anak menulis teks yang cukup untuk mengisi aliran yang dialihkan. Proses induk akan menunggu tanpa batas waktu agar proses anak keluar. Proses anak akan menunggu tanpa batas waktu bagi induk untuk membaca dari aliran penuh StandardOutput .

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:
//      ' 49,800.20%
//      Line 500 of 500 written: 49,900.20%
//      '
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:
'      ' 49,800.20%
'      Line 500 of 500 written: 49,900.20%
'      '

Ada masalah serupa saat Anda membaca semua teks dari output standar dan aliran kesalahan standar. Contoh berikut melakukan operasi baca di kedua aliran. Ini menghindari kondisi kebuntuan dengan melakukan operasi baca asinkron pada StandardError aliran. Kondisi kebuntuan menghasilkan jika panggilan p.StandardOutput.ReadToEnd proses induk diikuti oleh p.StandardError.ReadToEnd dan proses anak menulis teks yang cukup untuk mengisi aliran kesalahannya. Proses induk akan menunggu tanpa batas waktu agar proses anak menutup alirannya StandardOutput . Proses anak akan menunggu tanpa batas waktu bagi induk untuk membaca dari aliran penuh 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.

Anda dapat menggunakan operasi baca asinkron untuk menghindari dependensi ini dan potensi kebuntuannya. Secara bergantian, Anda dapat menghindari kondisi kebuntuan dengan membuat dua utas dan membaca output setiap aliran pada utas terpisah.

Berlaku untuk

Lihat juga