Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.Writeline() not working

I'm creating a c# winforms project that can be run as a GUI or can be operated from the command line. Currently, I can process command line input and arguments. I can run the program from command line and I can use the program to process the arguments. But Console.Writeline() does absolutely nothing. Any clue why that could be?

like image 593
novacara Avatar asked Aug 06 '09 19:08

novacara


People also ask

How do I show the console WriteLine in Visual Studio?

In Visual Studio uppermost menu choose Debug > Windows > Output. It shows all Console. WriteLine("Debug MyVariable: " + MyVariable) when you get to them.

How does console WriteLine work?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

How do I print a console WriteLine?

To print a message to the console, we use the WriteLine method of the Console class. The class represents the standard input, output, and error streams for console applications. Note that Console class is part of the System namespace. This line was the reason to import the namespace with the using System; statement.

How do I view console output in Visual Studio 2019?

In Visual Studio choose VIEW > OUTPUT. You will see the results above in this output window after changing two settings below.


1 Answers

For the most part, see the answer here. However, I would like to point out the existence of the FreeConsole() API call, which allows you to gracefully close the console.

[DllImport("kernel32.dll")]
static extern int FreeConsole() 

One thing I'd like to note: you may see some weirdness of a command prompt appearing in front of your console output, if you're launching from an existing console and attaching to that with AttachConsole (as opposed to AllocConsole).

This is a timing issue which is hard to work around. If that's a problem, set your application to be a Console application like the others suggested. It will have the effect of no command prompt appearing until the application closes however, which might not be what you want if you're opening a winform.

In response to your comment: it's either AttachConsole or AllocConsole. The example I linked tries to attach to an existing console first. If that fails (most likely because it doesn't exist), it creates a new console window instead.

If you find a way to have the best of both worlds in terms of command-line behavior and GUI interactive mode, please let me know. I haven't done any in-depth searching for a solution, but I have a few minor apps that would benefit.

By the way: if you plan on using pipes on your command line (redirecting output to a file for example), that won't work like this unfortunately.

like image 200
Thorarin Avatar answered Oct 03 '22 19:10

Thorarin