Process.StandardError Properti

Definisi

Mendapatkan aliran yang digunakan untuk membaca output kesalahan aplikasi.

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

Nilai Properti

Yang StreamReader dapat digunakan untuk membaca aliran kesalahan standar aplikasi.

Atribut

Pengecualian

Aliran StandardError belum ditentukan untuk pengalihan; pastikan RedirectStandardError diatur ke true dan UseShellExecute diatur ke false.

-atau-

Aliran StandardError telah dibuka untuk operasi baca asinkron dengan BeginErrorReadLine().

Contoh

Contoh berikut menggunakan net use perintah bersama dengan argumen yang disediakan pengguna untuk memetakan sumber daya jaringan. Kemudian membaca aliran kesalahan standar perintah net dan menulisnya ke konsol.

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());
}
use myProcess = new Process()
let myProcessStartInfo = ProcessStartInfo("net ", $"use {args[0]}")

myProcessStartInfo.UseShellExecute <- false
myProcessStartInfo.RedirectStandardError <- true
myProcess.StartInfo <- myProcessStartInfo
myProcess.Start() |> ignore

let myStreamReader = myProcess.StandardError
// Read the standard error of net.exe and write it on to console.
printfn $"{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

Keterangan

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

Note

Untuk menggunakan StandardError, Anda harus mengatur ProcessStartInfo.UseShellExecute ke false, dan Anda harus mengatur ProcessStartInfo.RedirectStandardError ke true. Jika tidak, membaca dari StandardError aliran akan melemparkan pengecualian.

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

Sebaliknya, BeginErrorReadLine memulai operasi baca asinkron pada StandardError aliran. Metode ini memungkinkan penanganan aktivitas yang ditunjuk untuk output aliran dan segera kembali ke pemanggil, yang dapat melakukan pekerjaan lain saat output aliran diarahkan ke penanganan aktivitas.

Operasi baca sinkron memperkenalkan dependensi antara penelepon yang membaca dari StandardError aliran dan penulisan proses anak ke aliran tersebut. Dependensi ini dapat mengakibatkan kondisi kebuntuan. Ketika penelepon membaca dari aliran yang dialihkan dari proses anak, itu tergantung pada anak. Pemanggil menunggu pada 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 turunan menunggu pada operasi tulis berikutnya hingga induk membaca dari aliran penuh atau menutup aliran. Kondisi kebuntuan menghasilkan ketika pemanggil dan proses turunan saling menunggu untuk menyelesaikan operasi, dan tidak dapat melanjutkan. 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;

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.
module Write500Lines

for i in 1. .. 500. do
    printfn $"Line {i} of 500 written: {i/500.:P2}";

eprintfn "Successfully wrote 500 lines.";
// 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.

Contoh berikut menunjukkan cara membaca dari aliran kesalahan yang dialihkan dan menunggu proses turunan keluar. Ini menghindari kondisi kebuntuan dengan memanggil p.StandardError.ReadToEnd sebelum p.WaitForExit. Kondisi kebuntuan dapat mengakibatkan jika proses induk memanggil p.WaitForExit sebelum p.StandardError.ReadToEnd dan proses anak menulis teks yang cukup untuk mengisi aliran yang dialihkan. Proses induk akan menunggu tanpa batas waktu agar proses turunan keluar. Proses turunan 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.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.
module STDErrorSync

open System.Diagnostics

let p = new Process()
p.StartInfo.UseShellExecute <- false
p.StartInfo.RedirectStandardError <- true
p.StartInfo.FileName <- "Write500Lines.exe"
p.Start() |> ignore

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

printfn $"\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.

Ada masalah serupa saat Anda membaca semua teks dari output standar dan aliran kesalahan standar. Contoh berikut melakukan operasi baca pada kedua aliran. Ini menghindari kondisi kebuntuan dengan melakukan operasi baca asinkron pada StandardError aliran. Kondisi kebuntuan menghasilkan jika proses induk memanggil p.StandardOutput.ReadToEnd diikuti oleh p.StandardError.ReadToEnd dan proses turunan menulis teks yang cukup untuk mengisi aliran kesalahannya. Proses induk akan menunggu tanpa batas waktu agar proses anak menutup alirannya StandardOutput . Proses turunan 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:
//      'ritten: 99,80%
//      Line 500 of 500 written: 100,00%
//      '
//
//      Error stream: Successfully wrote 500 lines.
module STDOutputAsync

open System.Diagnostics

let p = new Process()
p.StartInfo.UseShellExecute <- false
p.StartInfo.RedirectStandardOutput <- true
let mutable eOut = ""
p.StartInfo.RedirectStandardError <- true
p.ErrorDataReceived.AddHandler(DataReceivedEventHandler(fun sender e -> eOut <- eOut + e.Data))

p.StartInfo.FileName <- "Write500Lines.exe"
p.Start() |> ignore

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

printfn $"The last 50 characters in the output stream are:\n'{output.Substring(output.Length - 50)}'"
printfn $"\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.

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.

Note

Anda tidak dapat mencampur operasi baca asinkron dan sinkron pada aliran yang dialihkan. Setelah aliran Process yang dialihkan dibuka dalam mode asinkron atau sinkron, semua operasi baca lebih lanjut pada aliran tersebut harus dalam mode yang sama. Misalnya, jangan ikuti BeginErrorReadLine dengan panggilan ke ReadLineStandardError di stream, atau sebaliknya. Namun, Anda dapat membaca dua aliran yang berbeda dalam mode yang berbeda. Misalnya, Anda dapat memanggil BeginOutputReadLine lalu memanggil ReadLineStandardError aliran.

Berlaku untuk

Lihat juga