Jan 14th, 2006, 01:33 AM
Automate Command Prompt Window (CMD), Redirect Output to Application [2003/2005]
The following code is a sample of how you can automate the command prompt window. It creates a new process in a thread with "cmd" as the filename (which starts a new command prompt window). A thread was used (although not required) as a preventative measure just in case the CMD window would hang for some reason. If it hangs and it is not started on a thread, then your application would hang as well until the cmd window was closed or killed.
The Process.StartInfo property contains a .RedirectStandardInput and .RedirectStandardOutput property that allows you to redirect the input and output associated with the process. The StandardOutput and StandardInput properties of the Process class are streamreaders and streamwriters, respectively, which you can set in order to send and receive the data.
The code below simply runs a command that is listed in a textbox, and outputs the results into a textbox. The entire project file is included below in the attachments.
EDIT - The original example below has a problem in the threading. See the 2005 example code in post 10 that corrects this issue
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
Private Sub CMDAutomate()
Dim myprocess As New Process
Dim StartInfo As New System.Diagnostics.ProcessStartInfo
StartInfo.FileName = "cmd" 'starts cmd window
StartInfo.RedirectStandardInput = True
StartInfo.RedirectStandardOutput = True
StartInfo.UseShellExecute = False 'required to redirect
myprocess.StartInfo = StartInfo
Dim SR As System.IO.StreamReader = myprocess.StandardOutput
Dim SW As System.IO.StreamWriter = myprocess.StandardInput
SW.WriteLine(txtCommand.Text) 'the command you wish to run.....
SW.WriteLine("exit") 'exits command prompt window
txtResults.Text = SR.ReadToEnd 'returns results of the command window
Last edited by gigemboy; Sep 12th, 2006 at 12:51 PM.
Click Here to Expand Forum to Full Width