Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert console.writeline to a string

I want a code that takes the text that was written on the console and put it on a string variable, plz. Something like this:

string s = Console.WriteLine(Invoke(o, null));

I want it with console because if I invoke it without it I can't get the text from it.

I hope you understand it.

like image 892
MeirKlemfner Avatar asked Sep 01 '25 10:09

MeirKlemfner


2 Answers

I got what I want

using (StringWriter stringWriter = new StringWriter())
        {
            Console.SetOut(stringWriter);
            Console.Write(mi.Invoke(o, null));
            string allConsoleOutput = stringWriter.ToString();

            MessageBox.Show(allConsoleOutput, "Output");
        }

thank for every one!

like image 108
MeirKlemfner Avatar answered Sep 04 '25 00:09

MeirKlemfner


You can't do this directly. I think you can somehow do it by getting the console window object or something like that, but it's really not worth the time to do that when you just want the output of Console.WriteLine.

There are a lot of overloads of Console.WriteLine, but in the end all the overloads will convert the parameter to a string, using ToString. So, to put the output of Console.WriteLine in a string variable, just call ToString on the argument.

string s = Invoke(o, null).ToString();

What if you want to both print, and store the output? You can do it like this:

string s = Invoke(o, null).ToString();
Console.WriteLine(s);
like image 26
Sweeper Avatar answered Sep 03 '25 23:09

Sweeper