C#: Launch Hidden Commandline Process and Retrieve its Output

Posted by OmegaMan at July 18, 2009

Category: How To

Tags: ,

Sometimes there may be a need to launch a command line operation which calls either an executable or a windows command and make it hidden. Within that operation data will be returned and the main code can process it. Here is a quick example to do that where a call to IPConfig is made. By simply setting the window style to hidden one can execute something without a window flashing at the user.

ProcessStartInfo psInfo = new System.Diagnostics.ProcessStartInfo(@"ipconfig");

psInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
psInfo.RedirectStandardOutput = true;
psInfo.UseShellExecute        = false;

Process GetIPInfo;
GetIPInfo = Process.Start( psInfo );

// We want to get the output from standard output
System.IO.StreamReader myOutput = GetIPInfo.StandardOutput;
GetIPInfo.WaitForExit( 3000 );

if ( GetIPInfo.HasExited )
    Console.WriteLine(myOutput.ReadToEnd());

Note This requires System.Diagnostics namespace to be included.

Share

1 Comment

  1. Way says

    There are some serious gotchas with Process namespace. If you don’t point ErrorOutput someplace, those errors raise either in your standard output or in your C# code. Probably not what you are going for there at all. When I did a lot of work with this, it seemed random, but I’m not certain if my memory is fuzzy here anymore or not.

    Additionally, if you have a large amount of output data, you can create an out of memory exception, as it just adds and adds to the virtual memory of the c# process. You may have to add a reader that continually pulls data off the output stream to reasonably deal with it if there is much volume to your data.

    Reply

Leave a comment

(required)
(required) (will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.