Reading values ​​already printed on the console

This may be completely impossible, but I was wondering if there is a way to read the values ​​that the console has already printed. For example, if the console printed

You travel north at a speed of 10 m / s

as a result Console.WriteLine("You are travelling north at a speed of 10m/s");, is there a way to read this line, and then, for arguments, by putting this value in a line?

Basically, I need to read what has already been output to the console, not user input. Is there any way?

Thanks in advance.

+4
source share
4 answers

Yes. There is a way out. You can Console.SetOutmethod.

Organize your main method as follows:

static void Main()
{
    using (StringWriter stringWriter = new StringWriter())
    {
         Console.SetOut(stringWriter);

         //All console outputs goes here
         Console.WriteLine("You are travelling north at a speed of 10m/s");

         string consoleOutput = stringWriter.ToString();
    }
}

Then consoleOutputmust have You are travelling north at a speed of 10m/s.

+5

, , Console.SetOut , , - .

:

public class OutputCapture : TextWriter, IDisposable
{
    private TextWriter stdOutWriter;
    public TextWriter Captured { get; private set; }
    public override Encoding Encoding { get { return Encoding.ASCII; } }

    public OutputCapture()
    {
        this.stdOutWriter = Console.Out;
        Console.SetOut(this);
        Captured = new StringWriter();
    }

    override public void Write(string output)
    {
        // Capture the output and also send it to StdOut
        Captured.Write(output);
        stdOutWriter.Write(output);
    }

    override public void WriteLine(string output)
    {
        // Capture the output and also send it to StdOut
        Captured.WriteLine(output);
        stdOutWriter.WriteLine(output);
    }
}

, :

void Main()
{
    // Wrap your code in this using statement...
    using (var outputCapture = new OutputCapture())
    {
        Console.Write("test");
        Console.Write(".");
        Console.WriteLine("..");
        Console.Write("Second line");
        // Now you can look in this exact copy of what you've been outputting.
        var stuff = outputCapture.Captured.ToString();
    }
}

, , , - List<string>, .

: - ( ), , NHibernate SQL Output LINQPad. ( Github repo NuGet): https://tomssl.com/2015/06/30/see-your-sql-queries-when-using-nhibernate-with-linqpad/

+1

, , . , , .

String a = "You are travelling north at a speed of 10m/s"
Console.WriteLine(a);
//Do anything you want with variable 'a'
0

, , String, , :

String consoleOutput = "You are travelling north at a speed of 10m/s"
Console.WriteLine(consoleOutput);

consoleOutput, .

0

Source: https://habr.com/ru/post/1625285/


All Articles