I'm looking for a way to insert a prefix (date and time) to every Console.Write[Line]. I'm looking for a recommended way to do so, just like the recommended way for changing the output is to use Console.SetOut.
I'm well aware that I can do String.Format("{0} {1}", DateTime.Now, msg), but I'm trying to leave that as my last resort.
The problem is that the output is changeable at run time, and the default one already appends the current time. If I append it on my code I will duplicate the date.
Is there such a thing? I'm using Monotouch, so I can only use libraries compiled for it.
Console. WriteLine writes your output to the console window opened by your application (think black window with white text that appears when you open the Command Prompt.)
In C# you can write or print to console using Console. WriteLine() or Console. Write(), basically both methods are used to print output of console.
Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. WriteLine(String) Writes the specified string value, followed by the current line terminator, to the standard output stream.
Console is a predefined class of System namespace. While Write() and WriteLine() both are the Console Class methods. The only difference between the Write() and WriteLine() is that Console. Write is used to print data without printing the new line, while Console.
You need to inherit from System.IO.TextWrite
, provide an Encoding
and overrides for e.g. WriteLine
and Write
. Store the original Console.Out
before changing with Console.setOut(x)
.
Here's a complete code example:
class PrefixedWriter : TextWriter
{
private TextWriter originalOut;
public PrefixedWriter()
{
originalOut = Console.Out;
}
public override Encoding Encoding
{
get { return new System.Text.ASCIIEncoding(); }
}
public override void WriteLine(string message)
{
originalOut.WriteLine(String.Format("{0} {1}", DateTime.Now, message));
}
public override void Write(string message)
{
originalOut.Write(String.Format("{0} {1}", DateTime.Now, message));
}
}
class Program
{
static void Main(string[] args)
{
Console.SetOut(new PrefixedWriter());
Console.WriteLine("test 1 2 3");
Console.ReadKey();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With