1

Is it possible to save what is typed in the console to a text file?

I know how to write and read from a text file, but I would like to know how to save what is typed in console itself to a text file.

So opening a console, typing text in the console itself (the black console screen), pressing Enter (or something else), and saving it to a file.

I haven't found any answers that work so I'm beginning to think it isn't possible.

On a side note; is there another name for that console application window? Or is it actually called console application window?

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93

4 Answers4

2

I haven't found any answers that work so I'm beginning to think it isn't possible.

What were you searching on? Console.ReadLine() returns a string, which is easily appended to a file:

using (var writer = new StreamWriter("ConsoleOutput.txt", append: true))
{
    string line = Console.ReadLine();
    writer.WriteLine(line);
}

Not all problems are solved on the web exactly as you require; break it up in smaller parts ("get string from console", "write string to file") and you will find the solution specific to your situation.


If this is about reading output from another process, this is a duplicate of How to spawn a process and capture its STDOUT in .NET?.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    Thank you, this is exactly what I wanted. As usual, the answer was more obvious than I realised. Thank you to everyone else for the fast replies and explanations. – Stuart Fowler Nov 25 '13 at 20:57
1

There are different approaches:

  1. Just use Console.ReadLine() for this in loop until some specific symbol. At the same time adding lines to a file stream.
  2. Another elegant solution to use Console.SetOUt method. Take a look on second example from MSDN. Pretty much what you need.
Anatolii Gabuza
  • 6,184
  • 2
  • 36
  • 54
1

Use this code to redirect console output to a text file with name consoleOut.txt

FileStream filestream = new FileStream("consoleOut.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
0

If it is no external console window, you can use Console.ReadLine() to get the typed string and save it to a file by calling e.g. File.WriteAllText, StreamWriter,...

Florian
  • 5,918
  • 3
  • 47
  • 86