Reputation:
I searched lots in internet to store the console application output screen in .txt file. I got the solution but i did not got the desired results. The problem is the text which was not display in console screen was stored in the notepad file. But the text displayed in the console screen was not stored in the notepad file.
For example,
using System;
using System.IO;
static void Main(string[] args)
{
Console.WriteLine("Text which is displayed in the the console output screen ");
FileStream filestream = new FileStream("notepad.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
Console.WriteLine("Text which is not displayed in the console output screen but it store in the the .txt file");
Console.ReadKey();
}
In above example
The line Console.WriteLine("Text which is displayed in the the console output screen ");
is just displayed in the console screen but it was not store in the notepad file
But the line Console.WriteLine("Text which is not displayed in the console output screen but it store in the the .txt file");
is not displayed in the console application screen instead of it was stored in the notepad file.
I need to store everything whatever displayed in the console screen even user given details too.
How do I do it?
As I am a beginner, I expecting the answer would be simple.
Thanks in advance!
Upvotes: 2
Views: 2712
Reputation: 14007
You can only assign one output stream to the console. So you will need a stream that does both, writing to the screen and to a file.
You can always get standard output stream of the console like this:
Stream consoleOutput = Console.GetStandardOutput();
If you want to use multiple outputs, you have to create a new stream class that will distribute the data to multiple streams. For that you will have to overwrite the Stream
class (not a full implementation, you will have to implement all other abstract members of Stream
, too):
public class MultiStream : Stream {
private readonly Stream[] m_children;
public MultiStream(params Stream[] children) {
m_children = children;
}
public override Write(byte[] buffer, int offset, int count) {
foreach(Stream child in m_children) {
child.Write(buffer, offset, count);
}
}
//...
}
Now you can use your MultiStream
to route your output to multiple streams:
FileStream filestream = new FileStream("notepad.txt", FileMode.Create);
MultiStream outStream = new MultiStream(filestream, Console.GetStandardOutput());
var streamwriter = new StreamWriter(outStream);
If you are OK to replace Console.WriteLine
, you could use a simpler way (assuming your streamwriter
variable is accessible):
public void WriteLineToScreenAndFile(string text) {
Console.WriteLine(text);
streamwriter.WriteLine(text);
}
You can replace all calls to Console.WriteLine with a call to that method.
Upvotes: 6