title: Command Prompt Batchfile output to VB textbox
body: <p>I have a number of batch files and I'm trying to wrap a GUI around them so they are easily available for some of my users all in one place.</p>
  
  <p>At the moment, I've got 2 buttons and a Textbox.  Each button calls the same batch file with a different working directory (though in production, the batch files will be different).  At the moment, all it does is call 'DIR /A /B" to list a directory contents.</p>
  
  <pre><code>DIR /A /B
  exit
  </code></pre>
  
  <p>I've got the following code: (Button 2 is identical, but with a different working directory)</p>
  
  <pre><code>Public Class Form1
  Dim P As New Process
  Dim SW As System.IO.StreamWriter
  
  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      AddHandler P.OutputDataReceived, AddressOf DisplayOutput
      P.StartInfo.CreateNoWindow() = True
      P.StartInfo.UseShellExecute = False
      P.StartInfo.WorkingDirectory = "C:\temp"
      P.StartInfo.RedirectStandardInput = True
      P.StartInfo.RedirectStandardOutput = True
      P.StartInfo.RedirectStandardError = True
      P.StartInfo.FileName = "c:\temp\dircmd.cmd"
      P.Start()
      P.SynchronizingObject = TextBox1
      Try
          P.BeginOutputReadLine()
          TextBox1.Text = TextBox1.Text &amp; vbCrLf &amp; "Begin output" &amp; vbCrLf
          SW = P.StandardInput
          SW.WriteLine()
          MsgBox("WriteLine()")
          SW.Dispose()
          SW.Close()
          MsgBox("StreamWriter Close")
          P.WaitForExit()
          P.CancelOutputRead()
          P.Close()
          MsgBox("Process Close")
      Catch ex As Exception
          MsgBox(ex.ToString())
      End Try
  End Sub
  
  Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
      Textbox1.AppendText(output.Data() &amp; vbCrLf)
  End Sub
  </code></pre>
  
  <p>My problem is that I'm getting the output from each command, however its getting duplicated.  First button, first time works fine.  Second button works, but everything is listed twice.  Going back to first button, everything is listed 3 times. I initially thought I needed to clear the StreamWriter buffer, but its not repeating old info, its just repeating new info and I'm not sure why. </p>
  
  <pre><code>Begin output
  
  C:\temp&gt;DIR /A /B 
  bob.txt
  dircmd.cmd
  LocationRouting.xml
  TempFrogsareNOTCool.txt
  Test.txt
  test2.txt
  Test3.txt
  
  C:\temp&gt;exit
  
  Begin output 2
  
  C:\&gt;DIR /A /B 
  C:\&gt;DIR /A /B 
  $Recycle.Bin
  $Recycle.Bin
  Config.Msi
  Config.Msi
  Documents and Settings  
  Documents and Settings
  &lt;snip&gt;
  
  C:\&gt;exit
  C:\&gt;exit
  </code></pre>