如何将C#输出消息分配给字符串变量?

时间:2016-04-14 15:00:34

标签: c#

喜欢,能够存储

string val = Console.WriteLine("Hello") 

或同等方式。类型铸造似乎也不起作用。

更新::好吧,我想记录任何Console.WriteLine()输出,所以问题是什么是实现它的最佳方法?

4 个答案:

答案 0 :(得分:3)

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

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

然后

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

让我问你:为什么?你想达到什么目的?我们可能会帮助你;)

编辑:asker说他想让Console.WriteLine写入文件(我猜也是如此)。

实现这一目标的方法可能是将自定义TextWriter设置为System.Console.Out,如下所述:https://msdn.microsoft.com/en-us/library/system.console.out%28v=vs.110%29.aspx

实际设置是使用Console.SetOut(https://msdn.microsoft.com/en-us/library/system.console.setout%28v=vs.110%29.aspx)。

不那么疯狂的方法是使用(例如)NLog - 然后只写Log.Info(“message”)并同时设置FileAppender和ConsoleAppender :)

在此处查看NLog:http://nlog-project.org/

来自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>

答案 1 :(得分:0)

你不想以那种方式存储它。首先创建字符串变量:

string val

然后根据需要使用字符串:

Console.WriteLine(val);

答案 2 :(得分:0)

如果要记录写入Console.Out的所有内容,可以创建自己的LoggingConsoleWriter,扩展TextWriter并将所有文本写入多个TextWriters,其中一个可以是日志文件。然后,您可以使用Console.SetOut()方法将标准输出设置为此类的实例:

// 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");
    }
}

或者,如果您只想登录字符串变量。您可以改为实例化StringWriter,如下所示:

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();
    }
}

答案 3 :(得分:0)

这是使用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);
}

然后在代码的其他地方,您可以像这样调用此方法:

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