Its really simple to read a console’s text (contents) in C#. This can be done using the Console.In.ReadLine() method. The Console and the Console.In classes exposes a loads of methods that are really handy. Here is a small snippet that tries to print the directories in blue color and the others in default color in console when you type dir.
string aConsoleReadLine = null;
ConsoleColor aDefaultConsoleColor = Console.ForegroundColor;
while ((aConsoleReadLine = Console.In.ReadLine()) != null) //Reading the text from the console and storing it in a local variable
{
if (aConsoleReadLine.Contains("<DIR>")) //Check if it is a directory
{
Console.ForegroundColor = ConsoleColor.Blue;
}
else
{
Console.ForegroundColor = aDefaultConsoleColor;
}
Console.WriteLine(string.Format("{0}", aConsoleReadLine));
}
To run the above mentioned snippet, create a console app and put this snippet in your main method. Then, open up command prompt. In the command prompt type dir | <your_built_exe>.exe. We use | so that we can get the output to our program.
Tags: C#, DoUNo, General Programming, Tips 'n' Tricks
