我在Visual Basic中做了一个应用程序,可以打开cmd并通过VPN将文件传输到Android接收器。它工作得很好,但我如何从CMD得到响应,以检查传输是否成功?
的示例代码公共类Form1
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Shell("cmd.exe /k" + "adb push C:UsersuserDesktopNewfolder1.png /sdcard/test")
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
Shell("adb connect " + TextBox1.Text)
btnSend.Enabled = True
btnConnect.Enabled = False
End Sub
结束类
我假设您想要获得adb命令的返回代码或std输出。无论哪种方式,您都需要启动自己的进程,而不是使用Shell命令,因为:
进程终止时可以返回退出码。但是,您不能使用Shell检索此退出代码,因为如果Shell等待终止,则返回零,而且还因为进程运行在与Shell不同的对象中。来自http://msdn.microsoft.com/en-us/library/xe736fyk%28v=vs.90%29.aspx
链接将向您展示如何设置返回退出代码的进程。相关代码为
Dim procID As Integer
Dim newProc As Diagnostics.Process
newProc = Diagnostics.Process.Start("C:WINDOWSNOTEPAD.EXE")
procID = newProc.Id
newProc.WaitForExit()
Dim procEC As Integer = -1
If newProc.HasExited Then
procEC = newProc.ExitCode
End If
MsgBox("Process with ID " & CStr(ProcID) & _
" terminated with exit code " & CStr(procEC))
如果您想要的不是返回代码,而是程序的标准输出,那么根据http://msdn.microsoft.com/en-us/library/vstudio/system.diagnostics.process.standardoutput?cs-save-lang=1&cs-lang=vb#code-snippet-4你可以通过下面的代码片段:
Imports System
Imports System.IO
Imports System.Diagnostics
Class IORedirExample
Public Shared Sub Main()
Dim args() As String = Environment.GetCommandLineArgs()
If args.Length > 1
' This is the code for the spawned process'
Console.WriteLine("Hello from the redirected process!")
Else
' This is the code for the base process '
Dim myProcess As New Process()
' Start a new instance of this program but specify the spawned version. '
Dim myProcessStartInfo As New ProcessStartInfo(args(0), "spawn")
myProcessStartInfo.UseShellExecute = False
myProcessStartInfo.RedirectStandardOutput = True
myProcess.StartInfo = myProcessStartInfo
myProcess.Start()
Dim myStreamReader As StreamReader = myProcess.StandardOutput
' Read the standard output of the spawned process. '
Dim myString As String = myStreamReader.ReadLine()
Console.WriteLine(myString)
myProcess.WaitForExit()
myProcess.Close()
End If
End Sub
End Class
当您自己尝试时,请记住必须包含
myProcessStartInfo.UseShellExecute = False