Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Propiedad Console.Error

 

Publicado: octubre de 2016

Obtiene el flujo de salida de error estándar.

Espacio de nombres:   System
Ensamblado:  mscorlib (en mscorlib.dll)

public static TextWriter Error {
	[HostProtectionAttribute(SecurityAction.LinkDemand, UI = true)]
	get;
}

Valor de propiedad

Type: System.IO.TextWriter

Objeto TextWriter que representa el flujo de salida de error estándar.

This standard error stream is set to the console by default. It can be set to another stream with the M:System.Console.SetError(System.IO.TextWriter) method. After the standard error stream is redirected, it can be reacquired by calling the M:System.Console.OpenStandardError method.

In console applications whose informational output is often redirected to a file, the standard error stream available through the P:System.Console.Error property can be used to display information to the console even if output is redirected. The following example displays product tables for 10 numbers at a time starting with 1. After every set of 10 numbers, the P:System.Console.Error property is used to ask the user whether to display the next set. If the standard output is redirected to a file, the user is still asked whether the routine should generate the next set of products.

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;
      }
   }
}

The following example is a command line utility named ExpandTabs that replaces tab characters in a text file with four spaces, the value defined by the tabSize variable. It redirects the standard input and output streams to files, but uses the P:System.Console.Error property to write the standard error stream to the console. It can be launched from the command line by supplying the name of the file that contains tab characters and the name of the output file.

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;
    }
}

The following example is a simple text file viewer that displays the contents of one or more text files to the console. If there are no command line arguments, or if any files passed as command line arguments do not exist, the example calls the M:System.Console.SetError(System.IO.TextWriter) method to redirect error information to a file, calls the M:System.Console.OpenStandardError method in the process of reacquiring the standard error stream, and indicates that error information was written to a file.

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 ViewFileText.Err.txt:
//     'file1.txt' does not exist.
//     'file2.txt' does not exist.

Note that the P:System.IO.StreamWriter.AutoFlush property is set to true before reacquiring the error stream. This ensures that output will be sent to the console immediately rather than buffered.

.NET Framework
Disponible desde 1.1
Silverlight
Disponible desde 2.0
Windows Phone Silverlight
Disponible desde 7.0
Volver al principio
Mostrar: