Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the application's output not shown?

Tags:

c#

.net

I have an application, that has the following Main:

static void Main(string[] args)
{
     Console.WriteLine("started");
     if (args.Length == 0)
     {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
          Application.Run(new Form1());
     }
     else
     {
          File.WriteAllText("./file.txt", "hello");
     }
}

I want it to support running from command line, to be used in some scripts, as well as running like a GUI app. However, if I run it from the command line, and pass it a parameter, I can see that the file gets created, but I don't see any of the output produced by Console.WriteLine. Why is that?

like image 475
Geo Avatar asked Jan 18 '23 17:01

Geo


2 Answers

I think I've found problem, please forgive me if I'm wrong.
When you create a GUI application and run it from a console window, its standard output stream is not sent to previously opened console window, so it's not shown.
But if you try to run yourexe.exe > test.txt you can see everything you wrote with Console.WriteLine

like image 133
Marco Avatar answered Jan 24 '23 22:01

Marco


It won't work becase:

That’s because the console window that launched your WinForms application belongs to the cmd.exe process, which is separate from your WinForms application process.

I found this in this article which is also offers some workaround with the AttachConsole Win32 method

like image 30
nemesv Avatar answered Jan 24 '23 23:01

nemesv