Console.OpenStandardOutput Method
Acquires the standard output stream.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
This method can be used to reacquire the standard output stream after it has been changed by the SetOut method.
Note |
|---|
The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: UI. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes. |
The following example illustrates the use of the OpenStandardOutput method. It replaces four consecutive space characters in a string with a tab character. To run it, you must supply two command-line arguments. The first is the name of an existing text file to redirect the standard input stream to. The second is the name of a file to redirect the standard output stream to. This file need not exist. If it does, its contents will be overwritten.
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) { StreamWriter writer = null; if (args.Length < 2) { Console.WriteLine(usageText); return 1; } try { // Attempt to open output file. writer = new StreamWriter(args[1]); // 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(new StreamReader(args[0])); } catch(IOException e) { TextWriter errorWriter = Console.Error; errorWriter.WriteLine(e.Message); errorWriter.WriteLine(usageText); return 1; } string line; while ((line = Console.ReadLine()) != null) { string newLine = line.Replace(("").PadRight(tabSize, ' '), "\t"); Console.WriteLine(newLine); } 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("INSERTTABS has completed the processing of {0}.", args[0]); return 0; } }
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note