Stuart Fowler
Stuart Fowler

Reputation: 15

How to save what is typed in console to a text file?

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?

Upvotes: 1

Views: 555

Answers (4)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

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.

Upvotes: 1

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

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);

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151588

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?.

Upvotes: 2

Florian
Florian

Reputation: 5994

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,...

Upvotes: 0

Related Questions