Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the recommended way to prefix Console.Write?

Tags:

c#

xamarin.ios

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.

like image 912
Jonas Stawski Avatar asked Apr 26 '12 20:04

Jonas Stawski


People also ask

Where does console write write to?

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.)

How do you write to console?

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.

What is console write line?

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.

What means console write?

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.


1 Answers

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();
    }
}
like image 64
ChristopheD Avatar answered Sep 24 '22 00:09

ChristopheD