If we compile the following code and run the resulting application, we will interact with it by entering our name, pressing enter, and pressing any key to exit. All of these actions are done on a console window.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your name: ");
var name = Console.ReadLine();
Console.WriteLine("Your name is {0} ", name);
Console.ReadKey();
}
}
}
Is it possible to save all of these actions to a text file such that I can make use of it as a log?
Edit:
I should explain the real scenario. I am writing a book about C#. I want to avoid attaching the screen shot of the console window to the book because I want to make the file size of my book as small as possible. Instead, I want to attach a text file showing the content of console window to the book. Adding additional code (for creating the text file) will complicate the code example, which in turn will make the reader get confused.
Okay, so the idea here is to change the reader/writer for console input and output to do what they did before but also write out to a log file. I made a Log class which should probably be extended so as to take the filename/path as a parameter, but it was important to have one so that the output stream could be synchronized.
Now that we’ve created these classes we’ll do the following right at the start of
Main:We’ll also need this at the end of
Main:It’s a somewhat quick and dirty write up. If you use this in production you’ll likely want to change a lot of the class/method names.