Jabir
Jabir

Reputation: 81

C# - Is there way to copy Console Content and save to file at the end of code as well as have it show up on Console while code is running?

I want to save everything that Console outputs to a .txt file after my code is done executing. I have tried few things like below and it works but while code is running, the console is blank and content is redirected to the file. I would like it to show on console and the file at the same time or at the end of code. Please try and see if you have a better way to do this.

            //Saving Console output to file
            Console.WriteLine("Please Enter File Name: \n");
            string fileName = Console.ReadLine();

            string filePath = @"C:\Desktop\Log.txt";
            
            FileStream filestream = new FileStream(filePath, FileMode.Create);
            var streamwriter = new StreamWriter(filestream);
            streamwriter.AutoFlush = true;
            Console.SetOut(streamwriter);
            Console.SetError(streamwriter);
            

Upvotes: 1

Views: 2124

Answers (2)

bschellekens
bschellekens

Reputation: 301

A @gunr2171 pointed out, there are libraries for this like Serilog and NLog that you can configure to log to both. The correct approach depends on the scope of your project. If you are writing something that is going into production, use one of these libraries. If this is just for a personal/school project, you can do something simple like a Log method that does both like so:

public class MyClass
{
  StringBuilder log = new StringBuilder();

  private void Log(string msg)
  {
    Console.WriteLine(msg);
    this.log.AppendLine(msg);
  }

  ~MyClass() => System.IO.File.AppendAllText("Path\To\File", log.ToString());
}

Upvotes: 2

gunr2171
gunr2171

Reputation: 17520

I'm assuming that whenever you write Console.WriteLine() you want that message to go to a text file, and also, optionally, to the terminal screen.

So make your own method that does that.

static void PrintMessage(string message)
{
    // if you want to print to the screen
    Console.WriteLine(message);

    // if you want to write to a file
    // note, there are more efficient ways to do this
    File.AppendAllText(SomeFilePath, message);

    // if you want more "sinks", then add more here
}

Now, in your program, instead of calling Console.WriteLine call PrintMessage.


This answer shows the fundamentals. Once you understand, then you can do some research on Serilog and other logging libraries.

Upvotes: 1

Related Questions