Search code examples
.netvb.netsystem.diagnostics

Command not executing when invoking windows cmd from vb.net app


I'm a bit of a .NET noob. I've been struggling trying to find a way to execute a command through a vb.net application and I found this thread so what I came up with, to map a drive to another server on the network was this;

Dim application As New ProcessStartInfo("cmd.exe")
Dim process As Process
process = process.Start(application)
Dim command As String = "net use x: \\webtest01\c$ /USER:daylight\robbery TakeItNGo" 'all fake obviously
process.StandardInput.WriteLine(command)
process.WaitForExit()
process.Close()

but when I run app, it sits for about 30seconds and then I get the windows command console popping up with the working directory set to E:\>

can someone tell me what I'm doing wrong please, this is the first time I'm doing this from a vb.net app


Solution

  • Your code need modifications

        Dim application As New ProcessStartInfo("cmd.exe") With 
                             {.RedirectStandardInput = True, .UseShellExecute = False}
        Dim process As New Process
        process = process.Start(application)
        Dim command As String = "net use x: \\webtest01\c$ /USER:daylight\robbery TakeItNGo"  _
                 & vbCrLf & "exit"
        process.StandardInput.WriteLine(command)
        process.WaitForExit()
        process.Close()
    

    To use standard input you need .RedirectStandardInput = True, .UseShellExecute = False (Process.StandardInput Property ). And "exit" command is necessary to end the cmd process.