Saturday, September 06, 2008

A C# class to make running, and capturing their output, command line/console applications “slick” and easy (From the author of PoshConsole)

Huddled Masses - NativeConsole.cs - Run console apps and get their output

“…

A while ago I wrote a little class for calling console apps from a .Net application, and I’ve been using it in several of my apps (most notably in PoshConsole) and it works great, but since the only place I’ve really published it is in PoshConsole, I thought I’d write it up here, and share it with you …

Basically, it’s a slick invisible event-based wrapper around the Windows native console. What I mean is, it calls AllocConsole when it’s instantiated to create a native console, and hides the console window so it doesn’t show up. This allows you to run any console app you need to from within your app without having it popup a black window.  Note this doesn’t let you run graphical consoles like EDIT.COM, but it can handle interactive apps like cmd.exe, batch files, or ftp.exe). All you really have to do is create one of my NativeConsole objects, handle its WriteOutputLine and WriteErrorLine events … and use its WriteInput method to send input or commands to the console app.

You can check out how it works in my WPF-based PoshConsole, and you can get the latest version of it from that project as well (it’s in \trunk\Huddled\Interop\NativeConsole.cs) but for now, here’s the single file source code, with a more liberal set of licenses than I allow for PoshConsole.

…”

Sometimes the only option is the call a command line/console application. I’ve run into that more times than I want to think about, and always seem to re-invent this wheel.

Well has taken the time to publish the work he’s done in this area, and I think that’s the wheel I’m going to go with in the future. His code handles areas where I’ve skimped on or just ignored and hoped wouldn’t run into…

I’ll stand on the shoulders of giants and all that… ;)

No comments: