Console.Error Свойство

Определение

Возвращает стандартный выходной поток сообщений об ошибках.

public:
 static property System::IO::TextWriter ^ Error { System::IO::TextWriter ^ get(); };
public static System.IO.TextWriter Error { get; }
member this.Error : System.IO.TextWriter
Public Shared ReadOnly Property Error As TextWriter

Значение свойства

TextWriter

Объект TextWriter, предоставляющий стандартный поток вывода ошибок.

Примеры

В следующем примере показана служебная программа командной строки с именем ExpandTabs, которая заменяет символы табуляции в текстовом файле четырьмя пробелами, значением, определенным переменной tabSize . Он перенаправляет стандартные входные и выходные потоки в файлы, но использует Error свойство для записи стандартного потока ошибок в консоль. Его можно запустить из командной строки, указав имя файла, содержащего символы табуляции и имя выходного файла.

using namespace System;
using namespace System::IO;

void main()
{
   const int tabSize = 4;
   array<String^>^args = Environment::GetCommandLineArgs();
   String^ usageText = "Usage: EXPANDTABSEX inputfile.txt outputfile.txt";
   StreamWriter^ writer = nullptr;
   
   if ( args->Length < 3 )
   {
      Console::WriteLine( usageText );
      return;
   }

   try
   {
      writer = gcnew StreamWriter( args[ 2 ] );
      Console::SetOut( writer );
      Console::SetIn( gcnew StreamReader( args[ 1 ] ) );
   }
   catch ( IOException^ e ) 
   {
      TextWriter^ errorWriter = Console::Error;
      errorWriter->WriteLine( e->Message );
      errorWriter->WriteLine( usageText );
      return;
   }

   int i;
   while ( (i = Console::Read()) != -1 )
   {
      Char c = (Char)i;
      if ( c == '\t' )
            Console::Write( ((String^)"")->PadRight( tabSize, ' ' ) );
      else
            Console::Write( c );
   }

   writer->Close();
   
   // Recover the standard output stream so that a 
   // completion message can be displayed.
   StreamWriter^ standardOutput = gcnew StreamWriter(Console::OpenStandardOutput());
   standardOutput->AutoFlush = true;
   Console::SetOut(standardOutput);
   Console::WriteLine( "EXPANDTABSEX has completed the processing of {0}.", args[ 0 ] );
   return;
}
using System;
using System.IO;

public class ExpandTabs
{
    private const int tabSize = 4;
    private const string usageText = "Usage: EXPANDTABSEX inputfile.txt outputfile.txt";

    public static void Main(string[] args)
    {
        StreamWriter writer = null;

        if (args.Length < 2) {
            Console.WriteLine(usageText);
            return;
        }

        try {
            writer = new StreamWriter(args[1]);
            Console.SetOut(writer);
            Console.SetIn(new StreamReader(args[0]));
        }
        catch(IOException e) {
            TextWriter errorWriter = Console.Error;
            errorWriter.WriteLine(e.Message);
            errorWriter.WriteLine(usageText);
            return;
        }
        int i;
        while ((i = Console.Read()) != -1) {
            char c = (char)i;
            if (c == '\t')
                Console.Write(("").PadRight(tabSize, ' '));
            else
                Console.Write(c);
        }
        writer.Close();
        // Recover the standard output stream so that a
        // completion message can be displayed.
        StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
        Console.WriteLine("EXPANDTABSEX has completed the processing of {0}.", args[0]);
        return;
    }
}
open System
open System.IO

let tabSize = 4
let usageText = "Usage: EXPANDTABSEX inputfile.txt outputfile.txt"

[<EntryPoint>]
let main args =
    if args.Length < 2 then
        printfn $"{usageText}"
    else 
        try
            use writer = new StreamWriter(args[1])
            Console.SetOut writer
            Console.SetIn(new StreamReader(args[0]))
            let mutable i = Console.Read()
            while i <> -1 do
                let c = char i
                if c = '\t' then
                    Console.WriteLine(("").PadRight(tabSize, ' '))
                else
                    printf $"{c}"
                i <- Console.Read()
            // Recover the standard output stream so that a
            // completion message can be displayed.
            use standardOutput = new StreamWriter(Console.OpenStandardOutput())
            standardOutput.AutoFlush <- true
            Console.SetOut standardOutput
            printfn $"EXPANDTABSEX has completed the processing of {args[0]}."
        with :? IOException as e ->
            let errorWriter = Console.Error
            errorWriter.WriteLine e.Message
            errorWriter.WriteLine usageText
    0
Imports System.IO

Public Class ExpandTabs
   Private Const tabSize As Integer = 4
   Private Const usageText As String = "Usage: EXPANDTABSEX inputfile.txt outputfile.txt"
   
   Public Shared Sub Main(args() As String)
      Dim writer As StreamWriter = Nothing

      If args.Length < 2 Then
         Console.WriteLine(usageText)
         Exit Sub
      End If
      
      Try
         writer = New StreamWriter(args(1))
         Console.SetOut(writer)
         Console.SetIn(New StreamReader(args(0)))
      Catch e As IOException
         Console.Error.WriteLine(e.Message)
         Console.Error.WriteLine(usageText)
         Exit Sub
      End Try
      
      Dim i As Integer = Console.Read()
      While i <> -1 
         Dim c As Char = Convert.ToChar(i)
         If c = ControlChars.Tab Then
            Console.Write("".PadRight(tabSize, " "c))
         Else
            Console.Write(c)
         End If
         i = Console.Read()
      End While
      writer.Close()
      
      ' Reacquire the standard output stream so that a
      ' completion message can be displayed.
      Dim standardOutput As New StreamWriter(Console.OpenStandardOutput)
      standardOutput.AutoFlush = True
      Console.SetOut(standardOutput)
      Console.WriteLine("EXPANDTABSEX has completed the processing of {0}.", args(0))
   End Sub
End Class

В следующем примере используется простое средство просмотра текстовых файлов, отображающее содержимое одного или нескольких текстовых файлов в консоли. Если аргументы командной строки отсутствуют или какие-либо файлы, переданные в качестве аргументов командной строки, отсутствуют, в примере вызывается SetError метод перенаправления сведений об ошибке в файл, вызывает OpenStandardError метод в процессе повторного получения стандартного потока ошибок и указывает, что сведения об ошибке были записаны в файл.

using System;
using System.IO;

public class ViewTextFile
{
   public static void Main()
   {
      String[] args = Environment.GetCommandLineArgs();
      String errorOutput = "";
      // Make sure that there is at least one command line argument.
      if (args.Length <= 1)
         errorOutput += "You must include a filename on the command line.\n";

      for (int ctr = 1; ctr <= args.GetUpperBound(0); ctr++)  {
         // Check whether the file exists.
         if (! File.Exists(args[ctr])) {
            errorOutput += String.Format("'{0}' does not exist.\n", args[ctr]);
         }
         else {
            // Display the contents of the file.
            StreamReader sr = new StreamReader(args[ctr]);
            String contents = sr.ReadToEnd();
            sr.Close();
            Console.WriteLine("*****Contents of file '{0}':\n\n",
                              args[ctr]);
            Console.WriteLine(contents);
            Console.WriteLine("*****\n");
         }
      }

      // Check for error conditions.
      if (! String.IsNullOrEmpty(errorOutput)) {
         // Write error information to a file.
         Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"));
         Console.Error.WriteLine(errorOutput);
         Console.Error.Close();
         // Reacquire the standard error stream.
         var standardError = new StreamWriter(Console.OpenStandardError());
         standardError.AutoFlush = true;
         Console.SetError(standardError);
         Console.Error.WriteLine("\nError information written to ViewTextFile.Err.txt");
      }
   }
}
// If the example is compiled and run with the following command line:
//     ViewTextFile file1.txt file2.txt
// and neither file1.txt nor file2.txt exist, it displays the
// following output:
//     Error information written to ViewTextFile.Err.txt
// and writes the following text to ViewTextFile.Err.txt:
//     'file1.txt' does not exist.
//     'file2.txt' does not exist.
open System
open System.IO

let args = Environment.GetCommandLineArgs()[1..]
let mutable errorOutput = ""
// Make sure that there is at least one command line argument.
if args.Length < 1 then
    errorOutput <- errorOutput + "You must include a filename on the command line.\n"

for file in args do
    // Check whether the file exists.
    if File.Exists file then
        errorOutput <- errorOutput + $"'{file}' does not exist.\n"
    else
        // Display the contents of the file.
        use sr = new StreamReader(file)
        let contents = sr.ReadToEnd()
        Console.WriteLine $"*****Contents of file '{file}':\n\n"
        Console.WriteLine contents
        Console.WriteLine "*****\n"

// Check for error conditions.
if not (String.IsNullOrEmpty errorOutput) then
    // Write error information to a file.
    Console.SetError(new StreamWriter(@".\ViewTextFile.Err.txt"))
    Console.Error.WriteLine errorOutput
    Console.Error.Close()
    // Reacquire the standard error stream.
    use standardError = new StreamWriter(Console.OpenStandardError())
    standardError.AutoFlush <- true
    Console.SetError standardError
    Console.Error.WriteLine "\nError information written to ViewTextFile.Err.txt"

// If the example is compiled and run with the following command line:
//     ViewTextFile file1.txt file2.txt
// and neither file1.txt nor file2.txt exist, it displays the
// following output:
//     Error information written to ViewTextFile.Err.txt
// and writes the following text to ViewTextFile.Err.txt:
//     'file1.txt' does not exist.
//     'file2.txt' does not exist.
Imports System.IO

Module ViewTextFile
   Public Sub Main()
      Dim args() As String = Environment.GetCommandLineArgs()
      Dim errorOutput As String = ""
      ' Make sure that there is at least one command line argument.
      If args.Length <= 1 Then
         errorOutput += "You must include a filename on the command line." +
                        vbCrLf
      End If
      
      For ctr As Integer = 1 To args.GetUpperBound(0)
         ' Check whether the file exists.
         If Not File.Exists(args(ctr)) Then
            errorOutput += String.Format("'{0}' does not exist.{1}",
                                         args(ctr), vbCrLf)
         Else
            ' Display the contents of the file.
            Dim sr As New StreamReader(args(ctr))
            Dim contents As String = sr.ReadToEnd()
            sr.Close()
            Console.WriteLine("***** Contents of file '{0}':{1}{1}",
                              args(ctr), vbCrLf)
            Console.WriteLine(contents)
            Console.WriteLine("*****{0}", vbCrLf)
         End If
      Next

      ' Check for error conditions.
      If Not String.IsNullOrEmpty(errorOutput) Then
         ' Write error information to a file.
         Console.SetError(New StreamWriter(".\ViewTextFile.Err.txt"))
         Console.Error.WriteLine(errorOutput)
         Console.Error.Close()
         ' Reacquire the standard error stream.
         Dim standardError As New StreamWriter(Console.OpenStandardError())
         standardError.AutoFlush = True
         Console.SetError(standardError)
         Console.Error.WriteLine("{0}Error information written to ViewTextFile.Err.txt",
                                 vbCrLf)
      End If
   End Sub
End Module
' If the example is compiled and run with the following command line:
'     ViewTextFile file1.txt file2.txt
' and neither file1.txt nor file2.txt exist, it displays the
' following output:
'     Error information written to ViewTextFile.Err.txt
' and writes the following text to ViewTextFile.Err.txt:
'     'file1.txt' does not exist.
'     'file2.txt' does not exist.

Обратите внимание, что StreamWriter.AutoFlush свойство задается true перед повторной настройкой потока ошибок. Это гарантирует, что выходные данные будут отправляться в консоль немедленно, а не буферичены.

Комментарии

По умолчанию для этого стандартного потока ошибок задана консоль. Его можно задать для другого SetError потока с помощью метода. После перенаправления стандартного потока ошибок его можно повторно запросить, вызвав OpenStandardError метод.

В консольных приложениях, информационные выходные данные которых часто перенаправляются в файл, стандартный поток ошибок, доступный через Error свойство, можно использовать для отображения сведений в консоли, даже если выходные данные перенаправляются. В следующем примере отображаются таблицы продуктов для 10 чисел за раз, начиная с 1. После каждого набора из 10 чисел свойство используется для того, чтобы задать пользователю вопрос о том, Error следует ли отображать следующий набор. Если стандартные выходные данные перенаправляются в файл, пользователю по-прежнему будет предложено создать следующий набор продуктов.

using System;

public class Example
{
   public static void Main()
   {
      int increment = 0;
      bool exitFlag = false;

      while (! exitFlag) {
         if (Console.IsOutputRedirected)
            Console.Error.WriteLine("Generating multiples of numbers from {0} to {1}",
                                    increment + 1, increment + 10);

         Console.WriteLine("Generating multiples of numbers from {0} to {1}",
                           increment + 1, increment + 10);
         for (int ctr = increment + 1; ctr <= increment + 10; ctr++) {
            Console.Write("Multiples of {0}: ", ctr);
            for (int ctr2 = 1; ctr2 <= 10; ctr2++)
               Console.Write("{0}{1}", ctr * ctr2, ctr2 == 10 ? "" : ", ");

            Console.WriteLine();
         }
         Console.WriteLine();

         increment += 10;
         Console.Error.Write("Display multiples of {0} through {1} (y/n)? ",
                             increment + 1, increment + 10);
         Char response = Console.ReadKey(true).KeyChar;
         Console.Error.WriteLine(response);
         if (! Console.IsOutputRedirected)
            Console.CursorTop--;

         if (Char.ToUpperInvariant(response) == 'N')
            exitFlag = true;
      }
   }
}
open System

let mutable increment = 0
let mutable exitFlag = false

while not exitFlag do
    if Console.IsOutputRedirected then
        Console.Error.WriteLine $"Generating multiples of numbers from {increment + 1} to {increment + 10}"

    Console.WriteLine $"Generating multiples of numbers from {increment + 1} to {increment + 10}"

    for i = increment + 1 to increment + 10 do
        Console.Write $"Multiples of {i}: "
        for j = 1 to 10 do
            Console.Write $"""{i * j}{if j = 10 then "" else ", "}"""

        Console.WriteLine()
    Console.WriteLine()

    increment <- increment + 10
    Console.Error.Write $"Display multiples of {increment + 1} through {increment + 10} (y/n)? "
    let response = Console.ReadKey(true).KeyChar
    Console.Error.WriteLine response
    if not Console.IsOutputRedirected then
        Console.CursorTop <- Console.CursorTop - 1 

    if Char.ToUpperInvariant response = 'N' then
        exitFlag <- true
Module Example
   Public Sub Main()
      Dim increment As Integer = 0
      Dim exitFlag As Boolean = False
      
      Do While Not exitFlag
         If Console.IsOutputRedirected Then
            Console.Error.WriteLine("Generating multiples of numbers from {0} to {1}",
                                    increment + 1, increment + 10)
         End If
         Console.WriteLine("Generating multiples of numbers from {0} to {1}",
                           increment + 1, increment + 10)
         For ctr As Integer = increment + 1 To increment + 10
            Console.Write("Multiples of {0}: ", ctr)
            For ctr2 As Integer = 1 To 10
               Console.Write("{0}{1}", ctr * ctr2, If(ctr2 = 10, "", ", "))
            Next
            Console.WriteLine()
         Next
         Console.WriteLine()
         
         increment += 10
         Console.Error.Write("Display multiples of {0} through {1} (y/n)? ",
                             increment + 1, increment + 10)
         Dim response As Char = Console.ReadKey(True).KeyChar
         Console.Error.WriteLine(response)
         If Not Console.IsOutputRedirected Then
            Console.CursorTop = Console.CursorTop - 1
         End If
         If Char.ToUpperInvariant(response) = "N" Then exitFlag = True
      Loop
   End Sub
End Module

Применяется к

См. также раздел