Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide output (not the window) in a console application?

Well, let me make it clear again. I have a console application with many classes, in each class there is at least one Console.WriteLine("text") line. I defined some arguments that when running the application, it output exactly what I wrote in classes. There, I want to define an argument that when I run the app with this argument, there will be no output on the console screen but the console window still appears. The argument maybe something like "-s". So is there any way I can do this without using the "if" condition in each class and passing an parameter through classes? Many thanks.

P/S: I've searched thru the internet and found out some articles related to this, but most of the answers were to hide the console window. I think this question should be what the others meant.

like image 981
Serge Wazuki Avatar asked Dec 07 '25 06:12

Serge Wazuki


2 Answers

Use Console.SetOut (http://msdn.microsoft.com/en-us/library/system.console.setout.aspx) and pass in a "null" text writer. The idea on -s perform a Console.SetOut(new StreamWriter()).

The example for the Console.SetOut method will help you get started.

In addition, you can easily add logging using this method.

like image 149
AMissico Avatar answered Dec 09 '25 23:12

AMissico


The Console.SetOut method throws a ArgumentNullException if you pass null directly; same for StreamWriter (if you pass a stream or if you pass a string.

What I use is passing the special Stream.Null field to a StreamWriter:

System.Console.SetOut(new System.IO.StreamWriter(System.IO.Stream.Null);

This redirect the stream to what is essentially the null device (/dev/null on *NIX machines).

like image 37
ShooShoSha Avatar answered Dec 09 '25 21:12

ShooShoSha