8 Replies - 2978 Views - Last Post: 29 March 2011 - 04:15 PM Rate Topic: -----

#1 MslMnMike  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 28-January 10

Wanting results from command line listed in listbox.

Posted 29 March 2011 - 09:44 AM

I am trying to develop an application and am still learning VB. I have a commandline that will list some applications that I need to make selectable to run certain processes based on what is selected. I have already found the MSDN stuff on using the RedirectStandardOutput class to add to streamwriter. What I need to do is read each line and add to a listbox so that the user can select each application. Please help me with some basics on how to read each line of the stream and add to a listbox. I found an MSDN article about using BeginOutputReadLine but was a little confusing. Here is that code.

Thanks.

' Define the namespaces used by this sample.
Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Namespace ProcessAsyncStreamSamples

   Class ProcessAsyncOutputRedirection
      ' Define static variables shared by class methods.
      Private Shared sortOutput As StringBuilder = Nothing
      Private Shared numOutputLines As Integer = 0

      Public Shared Sub SortInputListText()

         ' Initialize the process and its StartInfo properties.
         ' The sort command is a console application that
         ' reads and sorts text input.
         Dim sortProcess As New Process()
         sortProcess.StartInfo.FileName = "Sort.exe"

         ' Set UseShellExecute to false for redirection.
         sortProcess.StartInfo.UseShellExecute = False

         ' Redirect the standard output of the sort command.  
         ' Read the stream asynchronously using an event handler.
         sortProcess.StartInfo.RedirectStandardOutput = True
         sortOutput = new StringBuilder()

         ' Set our event handler to asynchronously read the sort output.
         AddHandler sortProcess.OutputDataReceived, _
                    AddressOf SortOutputHandler

         ' Redirect standard input as well.  This stream
         ' is used synchronously.
         sortProcess.StartInfo.RedirectStandardInput = True

         ' Start the process.
         sortProcess.Start()

         ' Use a stream writer to synchronously write the sort input.
         Dim sortStreamWriter As StreamWriter = sortProcess.StandardInput

         ' Start the asynchronous read of the sort output stream.
         sortProcess.BeginOutputReadLine()

         ' Prompt the user for input text lines.  Write each 
         ' line to the redirected input stream of the sort command.
         Console.WriteLine("Ready to sort up to 50 lines of text")

         Dim inputText As String
         Dim numInputLines As Integer = 0
         Do
            Console.WriteLine("Enter a text line (or press the Enter key to stop):")

            inputText = Console.ReadLine()
            If Not String.IsNullOrEmpty(inputText) Then
               numInputLines += 1
               sortStreamWriter.WriteLine(inputText)
            End If
         Loop While Not String.IsNullOrEmpty(inputText) AndAlso numInputLines < 50
         Console.WriteLine("<end of input stream>")
         Console.WriteLine()

         ' End the input stream to the sort command.
         sortStreamWriter.Close()

         ' Wait for the sort process to write the sorted text lines.
         sortProcess.WaitForExit()

         If Not String.IsNullOrEmpty(numOutputLines) Then
            ' Write the formatted and sorted output to the console.
            Console.WriteLine(" Sort results = {0} sorted text line(s) ", _
                              numOutputLines)
            Console.WriteLine("----------")
            Console.WriteLine(sortOutput)
         Else
            Console.WriteLine(" No input lines were sorted.")
         End If

         sortProcess.Close()
      End Sub 

      Private Shared Sub SortOutputHandler(sendingProcess As Object, _
         outLine As DataReceivedEventArgs)

         ' Collect the sort command output.
         If Not String.IsNullOrEmpty(outLine.Data) Then
            numOutputLines += 1

            ' Add the text to the collected output.
            sortOutput.Append(Environment.NewLine + "[" _
                         + numOutputLines.ToString() + "] - " _
                         + outLine.Data)
         End If
      End Sub 
   End Class  
End Namespace 



Is This A Good Question/Topic? 0
  • +

Replies To: Wanting results from command line listed in listbox.

#2 3P1C_F@!l  Icon User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 98
  • Joined: 01-March 11

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 10:04 AM

There are a number of ways to go about this but I would think the most simple(maybe not the best) would be..


a = reader.readline()
b = reader.readline()
c = reader.readline()
d = reader.readline()
e = reader.readline()

        ListBox1.Items.Add(a)
        ListBox1.Items.Add(B)/>
        ListBox1.Items.Add(c)
        ListBox1.Items.Add(d)
        ListBox1.Items.Add(e)



Was This Post Helpful? 0
  • +
  • -

#3 MslMnMike  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 28-January 10

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 10:28 AM

View Post3P1C_F@!l, on 29 March 2011 - 10:04 AM, said:

There are a number of ways to go about this but I would think the most simple(maybe not the best) would be..


a = reader.readline()
b = reader.readline()
c = reader.readline()
d = reader.readline()
e = reader.readline()

        ListBox1.Items.Add(a)
        ListBox1.Items.Add(B)/>
        ListBox1.Items.Add(c)
        ListBox1.Items.Add(d)
        ListBox1.Items.Add(e)




I am a little rusty but how would I do an enumeration or loop due to the number of items will be unknown. Basically like a for each X in reader, do item.add. forgive my sloppy syntax.
Was This Post Helpful? 0
  • +
  • -

#4 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 10:46 AM

Update the list box here:

inputText = Console.ReadLine()
If Not String.IsNullOrEmpty(inputText) Then
    numInputLines += 1
    sortStreamWriter.WriteLine(inputText)
End If


Was This Post Helpful? 0
  • +
  • -

#5 MslMnMike  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 28-January 10

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 11:01 AM

View Postn8wxs, on 29 March 2011 - 10:46 AM, said:

Update the list box here:

inputText = Console.ReadLine()
If Not String.IsNullOrEmpty(inputText) Then
    numInputLines += 1
    sortStreamWriter.WriteLine(inputText)
End If



Thanks I will give that a shot and see what I get.
Was This Post Helpful? 0
  • +
  • -

#6 MslMnMike  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 28-January 10

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 02:21 PM

Ok so this is what I got which seemed to get the data from what I can tell from the error due to it adding all the data on one line so it is getting a memory error. How would I get each line and add to the arraylist? I am getting this Exception error.

System.OutOfMemoryException was unhandled
  Message=Exception of type 'System.OutOfMemoryException' was thrown.
  Source=mscorlib
  StackTrace:
       at System.Collections.ArrayList.set_Capacity(Int32 value)
       at System.Collections.ArrayList.EnsureCapacity(Int32 min)
       at System.Collections.ArrayList.Add(Object value)
       at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\Michael\AppData\Local\Temporary Projects\WindowsApplication1\Form1.vb:line 26
       at System.Windows.Forms.Control.onclick(EventArgs e)
       at System.Windows.Forms.Button.onclick(EventArgs e)
       at System.Windows.Forms.Button.onmouseup(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativewindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativewindow.WndProc(Message& m)
       at System.Windows.Forms.Nativewindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 



This is the code that I have so far.

Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' This is the code for the base process
        Dim myProcess As New Process()
        ' Start a new instance of this program but specify the 'spawned' version.
        Dim myProcessStartInfo As New ProcessStartInfo("cmd.exe", "net start")
        myProcessStartInfo.UseShellExecute = False
        myProcessStartInfo.RedirectStandardOutput = True
        myProcess.StartInfo = myProcessStartInfo
        myProcess.Start()
        Dim myStreamReader As StreamReader = myProcess.StandardOutput
        ' Read the standard output of the spawned process.
        Dim myString As String = myStreamReader.ReadToEnd()
        Dim list As New ArrayList
        Dim count As Integer
        Do While Not String.IsNullOrEmpty(myString)
            list.Add(myString)

        Loop

        For count = 0 To list.Count - 1
            lstBxApps.Items.Add(count)
        Next


        myProcess.WaitForExit()
        myProcess.Close()
    End Sub
End Class


Was This Post Helpful? 0
  • +
  • -

#7 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 03:36 PM

If myString has a value when will this loop ever exit????

Do While Not String.IsNullOrEmpty(myString)
            list.Add(myString)


Was This Post Helpful? 0
  • +
  • -

#8 MslMnMike  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 28-January 10

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 03:58 PM

View Postn8wxs, on 29 March 2011 - 03:36 PM, said:

If myString has a value when will this loop ever exit????

Do While Not String.IsNullOrEmpty(myString)
            list.Add(myString)



I actually got it to work another way but now I need to find out how to delete the empty lines or items in the array.

Imports System
Imports System.Text
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        ' This is the code for the base process
        Dim myProcess As New Process()
        ' Start a new instance of this program but specify the 'spawned' version.
        Dim myProcessStartInfo As New ProcessStartInfo("ipconfig")
        myProcessStartInfo.UseShellExecute = False
        myProcessStartInfo.RedirectStandardOutput = True
        myProcess.StartInfo = myProcessStartInfo
        myProcess.Start()
        Dim myStreamReader As StreamReader = myProcess.StandardOutput
        ' Read the standard output of the spawned process.
        Dim myString As String = myStreamReader.ReadLine()
        Dim list As New ArrayList
        
        Do Until myString Is Nothing
            lstBxApps.Items.Add(myString.Trim)
            myString = myStreamReader.ReadLine
        Loop
        
        myProcess.WaitForExit()
        myProcess.Close()
    End Sub
End Class


Was This Post Helpful? 0
  • +
  • -

#9 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Wanting results from command line listed in listbox.

Posted 29 March 2011 - 04:15 PM

Don't copy the line read from the file directly to the destination. Use a temporary string instead. Trim the temporary string and if the trimmed temporary string's length is zero skip adding it to the destination.

This post has been edited by n8wxs: 29 March 2011 - 04:17 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1