Thursday, August 18, 2022

[FIXED] How to put all console output in a file but also display it on console C#?

Issue

How I do this in C#? I know about Console.SetOut() and it's not what i want since i get nothing on my console and everything goes to file. How I do to make both write in text file and display on Console? Is there any smart way or I need to go the hard and tedious route of Check file exists, Open File, Write, Close File after each Console.WriteLine() function


Solution

You could use a simple logger class:

class Logger {
    string LogFilePath { get; set; }

    void WriteLine(string msg) {
        Console.WriteLine(msg);
        System.IO.File.AppendAllText(LogFilePath, msg + '\n');
    }
}

Usage:

var logger = new Logger { LogFilePath = "text file path" };
logger.WriteLine("Write this to the console and append to the logfile");


Answered By - ayylmao
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.