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

天大地大妈咪最大 提交于 2019-12-06 11:14:08

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.

Use these methods to redirect output (programmatically):

    Console.SetIn(...);
    Console.SetOut(...);
    Console.SetError(...);

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).

app.exe > nul

redirects output to nowhere. FYI: Using command redirection operators

Have you come across Console.Clear(), you could call this in a way that makes it appear no text at all was output.

As for avoiding having to separately define this in each class you should look at inheritance. This allows you to define the functionality in one place and each 'sub' class will inherit this.

You could use log4net to define the items you want to log. It allows you to log regarding log level, regarding which class you want to log and so on.

This worked pretty well for me!:

Console.SetOut(StreamWriter.Null);
Console.SetError(StreamWriter.Null);

This doesn't work:

Console.SetOut(null);
Console.SetError(null);

It results in an ArgumentNullException.

This doesn't work:

Console.SetOut(new StreamWriter(null));
Console.SetError(new StreamWriter(null));

Because it is ambiguous between new StreamWriter(string path) and new StreamWriter(Stream stream).

And finally, neither of these work:

Console.SetOut(new StreamWriter(default(string)));
Console.SetError(new StreamWriter(default(Stream)));

Because they also result in an ArgumentNullException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!