Submitted byCategory
Review Cycle
.
Public
Joachim Mutter/sysarc
on 08/07/2009 at 02:25 PM
Programmierung

Using a Console Application as a filter

If you want to use a console application as a kind of filter with input redirection, you must check if there are valid characters in the input buffer.
Reading from the inputbuffer is not the problem, this could be done by using Console.In.Read() but if you call an application without a redirct, the app will wait until you type in a some charachters and quit that with <Enter>. Also peek waits until you type in something.
But this is not the normal behavior the user expects. If you call the app, you expect that something happens, like showing help, but not waiting until I type in something!

So during a long time of grabbing web I found the function Console.KeyAvailable(). With that you are able to check, if there is something in the input buffer. But if you use this and redirect the buffer by a pipe, the app throws an exception InvalidOperationException, because the console input was redirected from a file, ecactly what I want to find out. By handling this special exception, we could use this behavior to decide, if the app was called without anything or with a redirection!

And that it is what I want to have in my application!

Code
Namespace Test
Module Upper
Sub Main(ByVal cmdArgs() As String)
' could be used to debug that stuff and simulate somethint like type test.xml | application
'Console.SetIn(New StreamReader("c:\table.xml"))

' ---------------------------------------------------------------------------------------------------------
' Ok, with this trick, we are able to find out, if there are characters in the in buffer
' to use thew app as a filter. in the way
' type table.xml | DataGenerator.exe > blubber.txt
' ---------------------------------------------------------------------------------------------------------

Try
If Not Console.KeyAvailable Then
ShowHelp(True)
Return
End If
Catch
' ---------------------------------------------------------------------------------------------------------
' This would happen, if there are a pipe into this application
' So the try catch could do the job, checking, if there is something in the inputBuffer
' ---------------------------------------------------------------------------------------------------------
'System.InvalidOperationException:
'Es kann nicht erkannt werden, ob eine Taste gedrückt wurde,
'wenn keine der Anwendungen eine Konsole besitzt, oder wenn
'die Konsoleneingabe aus einer Datei umgeleitet wurde.
'Verwenden Sie Console.In.Peek.
End Try

Dim sb As StringBuilder = New StringBuilder()
While Console.In.Peek <> -1
Dim line As String = Console.In.ReadLine()
sb.Append(line).AppendLine()
End While
System.Console.WriteLine(sb.ToString().Upper())
End Sub

function ShowHelp()
System.Console.WriteLine("Usage: echo test | upper.exe")
End Sub
End Module
End Namespace