1

Like, being able to store

string val = Console.WriteLine("Hello") 

or equivalent way. Type casting doesn't seem to work neither.

Update:: Well, I want to log whatever Console.WriteLine() outputs, so question is what is the best way to accomplish that?

3
  • Don't do that. Just store the string itself. Commented Apr 14, 2016 at 15:01
  • You can store the string and then use it afterwards: string val = "Hello" and then Console.WriteLine(val); Commented Apr 14, 2016 at 15:03
  • Console.WriteLine() returns void (nothing). So there is no output to store. Commented Apr 14, 2016 at 15:04

4 Answers 4

3
var s = "Hello";
Console.WriteLine(s);

or

Func<string,string> ConsoleWriteLine = input => {Console.WriteLine(input); return input;};

and then

var x = ConsoleWriteLine("Hello"); // x == "Hello" now.

Let me ask you though: why? What are you trying to accomplish? We might help you with that instead ;)

EDIT: asker said he wants the Console.WriteLine to write to the file (I'm guessing: as well).

A way to accomplish that might be to have a custom TextWriter set to System.Console.Out, as described here: https://msdn.microsoft.com/en-us/library/system.console.out%28v=vs.110%29.aspx

The actual setting is using Console.SetOut (https://msdn.microsoft.com/en-us/library/system.console.setout%28v=vs.110%29.aspx).

The less insane way to do it would be to use (e.g.) NLog - then just write Log.Info("message") and have both FileAppender and ConsoleAppender set up :)

Check the NLog here: http://nlog-project.org/

Relevant config example from https://github.com/NLog/NLog/wiki/Tutorial#multiple-targets:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
        <target name="console" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Trace" writeTo="logfile" />
        <logger name="*" minlevel="Info" writeTo="console" />
    </rules>
</nlog>
Sign up to request clarification or add additional context in comments.

1 Comment

Would like to write System.Console.WriteLIne() message to the file somewhere, what is the best way to accomplish that?
0

You dont want to store it that way. First create the string variable:

string val

Then use the string for whatever you want:

Console.WriteLine(val);

Comments

0

If you want to log all things written to Console.Out, you can create your own LoggingConsoleWriter that extends TextWriter and writes all text to multiple TextWriters, one of which can be a log-file. Then, you can set the standard output to an instance of this class using the Console.SetOut()-method:

// This class writes to two different outputs, one of which can be the log
public class LoggingConsoleWriter : TextWriter
{
    private readonly TextWriter _output;
    private readonly TextWriter _log;

    public LoggingConsoleWriter(TextWriter output, TextWriter log)
    {
        _output = output;
        _log = log;
    }

    public override void Write(char value)
    {
        _output.Write(value);
        _log.Write(value);
    }

    public override Encoding Encoding => _output.Encoding;
} 

class Program
{
    static void Main(string[] args)
    {
        var logOutput = new StreamWriter(File.OpenWrite("log.txt"));
        var newOutput = new LoggingConsoleWriter(Console.Out, logOutput);

        // Redirect all Console.WriteX calls to write to newOutput
        Console.SetOut(newOutput);

        // This call will write to logOutput and the original Console.Out
        // through the LoggingConsoleWriter
        Console.WriteLine("Hello");
    }
}

Alternatively, if you just want to log to a string variable. You can instantiate a StringWriter instead, like so:

class Program
{
    static void Main(string[] args)
    {

        var sw = new StringWriter();
        var newOutput = new LoggingConsoleWriter(Console.Out, logOutput);

        // Redirect all Console.WriteX calls to write to newOutput
        Console.SetOut(newOutput);

        // This call will write to the StringWriter and the original Console.Out
        // through the LoggingConsoleWriter
        Console.WriteLine("Hello");

        // Retrieve the currently written values
        string output = sw.GetStringBuilder().ToString();
    }
}

Comments

0

Here's a quick and dirty way to accomplish what you're trying to do using TraceListeners:

public static void WriteToLog(string _logstring)
{
            string filepath = @"C:\myFilePath\fileName"

            Trace.Listeners.Clear();

            TextWriterTraceListener twtl = new TextWriterTraceListener(filepath + ".log");
            ConsoleTraceListener ctl = new ConsoleTraceListener(false);

            Trace.Listeners.Add(twtl);
            Trace.Listeners.Add(ctl);
            Trace.AutoFlush = true;
            Trace.WriteLine(_logstring);
}

Then elsewhere in your code you can call this method like this:

WriteToLog("This will be written to a file and print on the console");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.