Redirecting the Standard Streams By Redirecting the standard streams, your program can read commands from a disk file, create log files, or even read input from a network connection. Redirection of the standard streams can be accomplished in two ways. First, when you execute a program on the command line, you can use the < and > operators to redirect Console.In and/or Console.Out, respectively.
For Example:
using System; class Test { public static void Main() { Console.WriteLine(“This is a test.”); } }
executing the program like this,
Test > log
will cause the line “This is a test.” To be written to a file called log.
However, there is a second way that you can redirect the standard streams that is under program control. To do so, you will use the SetIn(), SetOut() and SetError() methods shown here, which are members of the Console:
static void SetIn(TextReader input) static void SetOut(TextWriter output) static void SetError(TextWriter output)
Thus, to redirect input, call SetIn(), specifying the desired stream. You can use any input stream as long as it is derived from TextReader. To redirect output to a file, specify a FileStream that is wrapped in a StreamWriter. The following program shows an example:
//Redirect Console.Out.
using System; using System.IO;
class Redirect { public static void Main() { StreamWriter output; try { output = new StreamWriter("C:/logfile.txt"); } catch(IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } //Direct standard output to the lof file. Console.SetOut(output); Console.WriteLine("Output Begins"); for(int i = 0; i < 10; i++) Console.WriteLine(i+1); Console.WriteLine("Output Ends"); output.Close(); } }
When you run this program, you won’t see any of the output on the screen, but the file logfile.txt will contain the following:
Output Begins 1 2 3 4 5 6 7 8 9 10 Output Ends
|
| Author: Bikash Patra 24 Nov 2006 | Member Level: Bronze Points : 0 |
Its a nice example for the beginners of console programming.
|