HOW TO:获取DOS命令输出结果

Public Class ConsoleOutputClass ConsoleOutput

Private Sub New()Sub New()
End Sub
Private Shared gWorkingDirectory As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal)

Public Shared Property WorkingDirectory()Property WorkingDirectory() As String
Get
Return gWorkingDirectory
End Get
Set(ByVal Value As String)
gWorkingDirectory = Value
End Set
End Property

Public Shared Function ExcuteCmd()Function ExcuteCmd(ByVal command As String) As String
Dim mResult As String = ""
Dim tmpProcess As New Process
With tmpProcess
With .StartInfo
.CreateNoWindow = True
.FileName = .EnvironmentVariables.Item("ComSpec")
.RedirectStandardOutput = True
.UseShellExecute = False
.Arguments = String.Format("/C {0}", command)
.WorkingDirectory = gWorkingDirectory
End With
Try
.Start()
.WaitForExit(5000)
mResult = .StandardOutput.ReadToEnd
Catch e As System.ComponentModel.Win32Exception
mResult = e.ToString
End Try
End With
Return mResult
End Function
End Class测试:

Private Sub Button1_Click()Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Console.WriteLine(ConsoleOutput.ExcuteCmd("NET TIME //192.168.0.223"))
End Sub
'结果
'//192.168.0.223 的当前时间是 2006-3-30 9:57
'
'命令成功完成。
本文介绍了一种通过创建进程并重定向标准输出的方式,来获取DOS命令执行结果的方法,并提供了一个VB.NET示例,展示了如何使用该方法来读取命令NET TIME //192.168.0.223的执行结果。
5398

被折叠的 条评论
为什么被折叠?



