ProcessStartInfo.RedirectStandardOutput Özellik

Tanım

Bir uygulamanın metin çıktısının akışa StandardOutput yazılıp yazılmadığını belirten bir değer alır veya ayarlar.

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

Özellik Değeri

true çıktısına StandardOutputyazılması gerekiyorsa; aksi takdirde , false. Varsayılan değer: false.

Örnekler

// 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

Açıklamalar

Bir Process metin standart akışına yazdığında, bu metin genellikle konsolda görüntülenir. akışı yeniden yönlendirmek StandardOutput için true olarak ayarlayarakRedirectStandardOutput, bir işlemin çıkışını işleyebilir veya gizleyebilirsiniz. Örneğin, metni filtreleyebilir, farklı biçimlendirebilir veya çıkışı hem konsola hem de belirlenmiş bir günlük dosyasına yazabilirsiniz.

Not

olarak ayarlamak UseShellExecutefalse istiyorsanız olarak ayarlamanız RedirectStandardOutputtruegerekir. Aksi takdirde, akıştan StandardOutput okumak bir özel durum oluşturur.

Yeniden yönlendirilen StandardOutput akış zaman uyumlu veya zaman uyumsuz olarak okunabilir. , ReadLineve ReadToEnd gibi Readyöntemler, işlemin çıkış akışında zaman uyumlu okuma işlemleri gerçekleştirir. İlişkili yazma işlemi akışına yazılana StandardOutput veya akışı kapatana kadar Process bu zaman uyumlu okuma işlemleri tamamlanmaz.

Buna karşılık, BeginOutputReadLine akışta StandardOutput zaman uyumsuz okuma işlemleri başlatır. Bu yöntem, akış çıkışı için belirlenmiş bir olay işleyicisini (bkz OutputDataReceived. ) etkinleştirir ve akış çıkışı olay işleyicisine yönlendirilirken diğer işleri gerçekleştirebilen çağırana hemen döner.

Not

Zaman uyumsuz çıkışı işleyen uygulama, çıkış arabelleğinin WaitForExit boşaltıldığından emin olmak için yöntemini çağırmalıdır.

Zaman uyumlu okuma işlemleri, çağıranın akıştan StandardOutput okuması ile bu akışa yazma alt işlemi arasında bir bağımlılık oluşturur. Bu bağımlılıklar kilitlenme koşullarına neden olabilir. Çağıran bir alt işlemin yeniden yönlendirilen akışından okursa, alt öğeye bağımlıdır. Çağıran, alt öğe akışa yazana veya akışı kapatana kadar okuma işlemini bekler. Alt işlem yeniden yönlendirilen akışını doldurmak için yeterli veri yazdığında, üst öğeye bağımlıdır. Alt işlem, üst öğe tam akıştan okuyana veya akışı kapatana kadar bir sonraki yazma işlemini bekler. Kilitlenme koşulu, çağıran ve alt işlem birbirinin bir işlemi tamamlamasını beklediğinde ve hiçbiri devam etmediğinde sonuçlanabilir. Çağıran ile alt işlem arasındaki bağımlılıkları değerlendirerek kilitlenmeleri önleyebilirsiniz.

Bu bölümdeki son iki örnek, Write500Lines.exeadlı bir yürütülebilir dosyayı başlatmak için yöntemini kullanırStart. Aşağıdaki örnek kaynak kodunu içerir.

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.

Aşağıdaki örnekte, yeniden yönlendirilen bir akıştan okuma ve alt işlemin çıkmasını bekleme adımları gösterilmektedir. Örnek, önce p.WaitForExitçağırarak p.StandardOutput.ReadToEnd kilitlenme koşulunu önler. Üst işlem daha önce p.StandardOutput.ReadToEnd çağırırsa p.WaitForExit ve alt işlem yeniden yönlendirilen akışı doldurmak için yeterli metin yazarsa kilitlenme koşulu oluşabilir. Üst işlem, alt işlemin çıkması için süresiz olarak bekler. Üst işlemin tam StandardOutput akıştan okuması için alt işlem süresiz olarak bekler.

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%
'      '

Hem standart çıkış hem de standart hata akışlarından tüm metinleri okuduğunuzda benzer bir sorun oluşur. Aşağıdaki örnek her iki akışta da bir okuma işlemi gerçekleştirir. Akışta zaman uyumsuz okuma işlemleri gerçekleştirerek kilitlenme koşulunu StandardError önler. Üst işlem tarafından çağrılması p.StandardOutput.ReadToEndp.StandardError.ReadToEnd ve alt işlemin hata akışını doldurmak için yeterli metin yazması durumunda kilitlenme koşulu oluşur. Üst işlem, alt işlemin akışını kapatması StandardOutput için süresiz olarak bekler. Üst işlemin tam StandardError akıştan okuması için alt işlem süresiz olarak bekler.

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.

Bu bağımlılıkları ve kilitlenme potansiyellerini önlemek için zaman uyumsuz okuma işlemlerini kullanabilirsiniz. Alternatif olarak, iki iş parçacığı oluşturup her akışın çıkışını ayrı bir iş parçacığında okuyarak kilitlenme durumundan kaçınabilirsiniz.

Şunlara uygulanır

Ayrıca bkz.