Leer en inglés

Compartir a través de


Console.SetOut(TextWriter) Método

Definición

Establece la propiedad Out para establecer el destino del objeto TextWriter.

C#
public static void SetOut (System.IO.TextWriter newOut);

Parámetros

newOut
TextWriter

Escritor de texto que se usará como la nueva salida estándar.

Excepciones

newOut es null.

El llamador no dispone del permiso requerido.

Ejemplos

En el ejemplo siguiente se muestra el uso del método SetOut. Reemplaza cuatro caracteres de espacio consecutivos en una cadena con un carácter de tabulación. Para ejecutarlo, debe proporcionar dos argumentos de línea de comandos. El primero es el nombre de un archivo de texto existente al que se va a redirigir el flujo de entrada estándar. El segundo es el nombre de un archivo al que se va a redirigir el flujo de salida estándar. No es necesario que exista este archivo. Si existe, se sobrescribirá su contenido.

C#
using System;
using System.IO;

public class InsertTabs
{
    private const int tabSize = 4;
    private const string usageText = "Usage: INSERTTABS inputfile.txt outputfile.txt";
    public static int Main(string[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine(usageText);
            return 1;
        }

        try
        {
            // Attempt to open output file.
            using (var writer = new StreamWriter(args[1]))
            {
                using (var reader = new StreamReader(args[0]))
                {
                    // Redirect standard output from the console to the output file.
                    Console.SetOut(writer);
                    // Redirect standard input from the console to the input file.
                    Console.SetIn(reader);
                    string line;
                    while ((line = Console.ReadLine()) != null)
                    {
                        string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t");
                        Console.WriteLine(newLine);
                    }
                }
            }
        }
        catch(IOException e)
        {
            TextWriter errorWriter = Console.Error;
            errorWriter.WriteLine(e.Message);
            errorWriter.WriteLine(usageText);
            return 1;
        }

        // Recover the standard output stream so that a
        // completion message can be displayed.
        var standardOutput = new StreamWriter(Console.OpenStandardOutput());
        standardOutput.AutoFlush = true;
        Console.SetOut(standardOutput);
        Console.WriteLine($"INSERTTABS has completed the processing of {args[0]}.");
        return 0;
    }
}

Comentarios

De forma predeterminada, la Out propiedad se establece en el flujo de salida estándar.

que StreamWriter encapsula un FileStream objeto se puede usar para enviar la salida a un archivo. Por ejemplo:

C#
Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
// First, save the standard output.
TextWriter tmp = Console.Out;
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
Console.SetOut(tmp);
Console.WriteLine("Hello World");
sw.Close();

El objeto real devuelto por Out puede ser un contenedor sincronizado alrededor del escritor de texto proporcionado.

Se aplica a

Producto Versiones
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

Consulte también