Link to home
Start Free TrialLog in
Avatar of kiranboi
kiranboi

asked on

Running DOS Commands from Code

Hi all,

Im using this line of code:
     Shell("CMD /K BUTIL -CLONE MTASLIN.8 MTASLIN.B")
to run an application called BUTIL.exe through a DOS window, however, before I use the DOS command above I need to be able to specify which directory the DOS promt should go to. Can someone tell me how to write more than 1 line of DOS code using Shell form VB.NET

Thanks :o)
ASKER CERTIFIED SOLUTION
Avatar of imnajam
imnajam
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Éric Moreau
Hi kiranboi,

In VB.Net, you should use Process.Start instead of Shell

Cheers!
for example

ipconfig release & ipconfig renew

you can also loop it as "cd c:\test\program & butil -clone mtaslin.8 mtaslin.b"

     Shell("CMD /K cd c:\testing\abc & BUTIL -CLONE MTASLIN.8 MTASLIN.B")
I agree with emoreau, the Process class has much better control over running DOS commands.

Here is a class to highlight:

Imports System.Diagnostics

Public Class DOSCommander

  Public Shared Function RunCommand(ByVal command As String, ByVal arguments As String, ByVal createWindow As Boolean, ByVal timeOut As Integer, ByRef output As String) As Integer

    Dim proc As New Process

    proc.StartInfo.Arguments = "/c " & command & " " & arguments
    proc.StartInfo.CreateNoWindow = Not createWindow
    proc.StartInfo.ErrorDialog = True
    proc.StartInfo.FileName = "cmd.exe"
    proc.StartInfo.RedirectStandardError = False
    proc.StartInfo.RedirectStandardInput = False
    proc.StartInfo.RedirectStandardOutput = True
    proc.StartInfo.UseShellExecute = False

    If createWindow Then
      proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal
    End If

    proc.Start()

    If timeOut = -1 Then
      proc.WaitForExit()
    Else
      proc.WaitForExit(timeOut)
    End If

    output = proc.StandardOutput.ReadToEnd()

    Return proc.ExitCode

  End Function

End Class

Sample usage:
  Dim output As String = ""
  DOSCommander.RunCommand("dir", "c:\windows", False, 3000, output)

Bob