How to Save Console.WriteLine Output to Text File
Try this example from this article - Demonstrates redirecting the Console output to a file
using System;
using System.IO;
static public void Main ()
{
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream ("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter (ostrm);
}
catch (Exception e)
{
Console.WriteLine ("Cannot open Redirect.txt for writing");
Console.WriteLine (e.Message);
return;
}
Console.SetOut (writer);
Console.WriteLine ("This is a line of text");
Console.WriteLine ("Everything written to Console.Write() or");
Console.WriteLine ("Console.WriteLine() will be written to a file");
Console.SetOut (oldOut);
writer.Close();
ostrm.Close();
Console.WriteLine ("Done");
}
Mirroring console output to a file
This may be some kind of more work, but I would go the other way round.
Instantiate a TraceListener
for the console and one for the log file; thereafter use Trace.Write
statements in your code instead of Console.Write
. It becomes easier afterwards to remove the log, or the console output, or to attach another logging mechanism.
static void Main(string[] args)
{
Trace.Listeners.Clear();
TextWriterTraceListener twtl = new TextWriterTraceListener(Path.Combine(Path.GetTempPath(), AppDomain.CurrentDomain.FriendlyName));
twtl.Name = "TextLogger";
twtl.TraceOutputOptions = TraceOptions.ThreadId | TraceOptions.DateTime;
ConsoleTraceListener ctl = new ConsoleTraceListener(false);
ctl.TraceOutputOptions = TraceOptions.DateTime;
Trace.Listeners.Add(twtl);
Trace.Listeners.Add(ctl);
Trace.AutoFlush = true;
Trace.WriteLine("The first line to be in the logfile and on the console.");
}
As far as I can recall, you can define the listeners in the application configuration making it possible to activate or deactivate the logging without touching the build.
write text on console and file simultaneously
This is not a full implementation but it should be enough to get you started down the path you seek.
class Program
{
static void Main(string[] args)
{
DualOut.Init();
Console.WriteLine("Hello");
Console.ReadLine();
}
}
public static class DualOut
{
private static TextWriter _current;
private class OutputWriter : TextWriter
{
public override Encoding Encoding
{
get
{
return _current.Encoding;
}
}
public override void WriteLine(string value)
{
_current.WriteLine(value);
File.WriteAllLines("Output.txt", new string[] { value });
}
}
public static void Init()
{
_current = Console.Out;
Console.SetOut(new OutputWriter());
}
}
If you run this code you will see that "Hello" is printed to both the console and to the file "Output.txt"
C# Console.Write print out in text file?
I don't know why you need to write in a file in your particular case but if you want Console.WriteLine
to write in a file you may use Console.SetOut(sw);
Console.WriteLine("Hello World");
FileStream fs = new FileStream("Test.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.WriteLine("Hello file");
sw.Close();
Saving the console application screen in .txt file
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.
Related Topics
Lock (Monitor) Internal Implementation in .Net
No Templates in Visual Studio 2017
Switch Case in C# - a Constant Value Is Expected
How to Include Quotes in a String
Directory.Getfiles of Certain Extension
Alternatives to Thread.Sleep()
Could Not Load File or Assembly 'Microsoft.Reportviewer.Common, Version=11.0.0.0
Multiple Colors in a C# .Net Label
Check If Instance Is of a Type
How to Provide Custom Cast Support for My Class
How Does Transactionscope Roll Back Transactions
Implementing Collectionchanged
Illustrating Usage of the Volatile Keyword in C#
Exclude Property on Update in Entity Framework
How to Check All Properties of an Object Whether Null or Empty