Recipe 14.31. Capturing a Console Application's OutputProblemYou want to capture and process the output of a console application in your program. SolutionSample code folder: Chapter 14\RedirectConsoleOutput Use the StartInfo portion of a Process object to redirect the output of a console application into your code. The redirected output appears as a standard StreamReader object. DiscussionThis recipe's sample code captures the network data generated by the ipconfig command-line tool and displays it in a ListBox control. Create a new Windows Forms application, and add three controls:
The controls should appear as in Figure 14-29. Figure 14-29. The controls for the redirected console output sampleNext, add the following code to the form's class template: Private Sub ActIPConfig_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles ActIPConfig.Click ' ----- Load the output of ipconfig.exe into a ListBox. Dim ipConfig As Process Dim oneLine As String Dim lineParts( ) As String ' ----- Remove any existing items. OutputData.Items.Clear( ) ' ----- Build and run the command. ipConfig = New Process( ) ipConfig.StartInfo.FileName = "ipconfig.exe" If (IncludeAll.Checked = True) Then _ ipConfig.StartInfo.Arguments = "/all" ipConfig.StartInfo.UseShellExecute = False ipConfig.StartInfo.RedirectStandardOutput = True ipConfig.StartInfo.CreateNoWindow = True ipConfig.Start( ) ' ----- Process each input line. Do While Not ipConfig.StandardOutput.EndOfStream ' ----- Ignore blank lines. oneLine = ipConfig.StandardOutput.ReadLine( ) If (Trim(oneLine) = "") Then Continue Do ' ----- Headings have no initial whitespace. If (oneLine = oneLine.TrimStart) Or _ (InStr(oneLine, ":") = 0) Then ' ----- A heading line or informational line. OutputData.Items.Add(oneLine.Trim) Else ' ----- A detail line. The format is: ' Title … : Data lineParts = oneLine.Trim.Split(":"c) lineParts(0) = Replace(lineParts(0), ". ", "") lineParts(1) = lineParts(1).Trim OutputData.Items.Add(vbTab & lineParts(0) & _ ":" & lineParts(1)) End If Loop ipConfig.WaitForExit( ) ipConfig.Dispose( ) End Sub Run the program, alter the IncludeAll field as desired, and click the ActProcess button. The ListBox control will be filled with the data output by the command-line ipconfig.exe program. Figure 14-30 shows some sample output for this program. Figure 14-30. Output from a console application, redirected to a ListBoxSome command-line programs, such as dir.exe, aren't really programs at all, but rather commands embedded within the command processor. For these programs, you need to use cmd.exe for the process filename and pass the actual command as an argument of the /c option: ipConfig.StartInfo.FileName = "cmd.exe" ipConfig.StartInfo.Arguments = "/c dir c:\temp" Unfortunately, you cannot prevent the command window from momentarily appearing when using cmd.exe as the process program. |