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

有帮助吗?

解决方案

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.

其他提示

Change your code to

Dim command As String = "/C net use x: \\webtest01\c$ /USER:daylight\robbery TakeItNGo" 
Dim application As New ProcessStartInfo("cmd.exe", command)
Dim process = process.Start(application)
process.WaitForExit()
process.Close()

The ProcessStartInfo class has a constructor that takes two arguments, the program file to start and the arguments to pass to this process.

However it is of paramount importance with CMD.exe to pass the flag /C on the command line otherwise the arguments will be ignored and the cmd.exe exits without looking at the arguments

More info on CMD flags

Of course all of this is valid if you are able to connect to the network resource with the credentials given. I would verify this as first step trying the same command on a normally opened command shell.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top