views:

133

answers:

3

I have a console application written in C# which processes some data then prints the results. Until the results are available there is a little animation ( / - \ | ) and progress percentage ( xx% ) which is constantly updating.

Obviously if the user redirects the output of my application this will be printed to the text file where output is redirected to. If possible I would like to avoid this.

So is there a way to detect if the output of my application is redirected? (if not I will close the question).

I am considering only showing the progress indicators when run with a specified parameter, but I'm hoping someone will have a good answer for me :)

Any input is appreciated, thank you :)

+1  A: 

You can't. Redirected output is totally and wholly outside the scope of the executing program. You can however add a commandline option to disable your pretty output so that it can be used redirected too.

Matthew Scharley
Just as I thought >.< Might just have to go with the cli parameter option.
Nippysaurus
What if I want to guess some default settings depending on whether the input goes from console or not? For example, in SQL parser it's good to print the resulting recordset when accepting commands from the keyboard, but be silent when parsing file. Or what if I care to output the Unicode BOM when writing to file? What are the patterns that should be used in these cases?
himself
@himself: If you want to handle stuff like writing a BOM, then ask for an output parameter. Depending on the OS, you can detect if you're running on a console, but it's convoluted to say the least, and it doesn't work on Windows/C# I don't think. Your simplest bet is to accept a `-q` (quiet) or similar option, or perhaps assume you're getting programmed input if you've got said option enabled to write to a file.
Matthew Scharley
+1  A: 

Rather than trying to determine whether or not the content is redirected, I would use Console.WriteLine (or Console.Out.WriteLine) to print your results and Console.Error.Write for your status updates. The screen output will show properly but not be reflected in the text file.

DocMax
Good idea, however it is rather misleading to write non-error data to stderr.
Nippysaurus
Misleading, yes, but a common practice all the same.
Matthew Scharley
+2  A: 

You can use the native method GetConsoleMode to see if stdout is going to a console or not.

This method is suggested by the remarks in the documentation for WriteConsole:

... determine whether the output handle is a console handle (one method is to call the GetConsoleMode function and check whether it succeeds)...

Stobor
Grannted, that means using unsafe native methods... But it's possible.
Stobor
P/Invoke is a pain, but it does look it'd be workable.
Matthew Scharley