在VB.net中获取shell命令的输出

Dav*_*lle 17 vb.net windows shell

我有一个VB.net程序,我在其中调用Shell函数.我想从文件中获取从此代码生成的文本输出.但是,这不是执行代码的返回值,所以我真的不知道如何.

这个程序是一个服务,但可以访问磁盘没有问题,因为我已经记录了其他信息.整个服务有多个线程,所以我还必须确保在写入文件时它尚未被访问.

com*_*ech 29

您将无法捕获Shell的输出.

您需要将其更改为进程,并且需要从进程中捕获标准输出(可能还有错误)流.

这是一个例子:

        Dim oProcess As New Process()
        Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
        oStartInfo.UseShellExecute = False
        oStartInfo.RedirectStandardOutput = True
        oProcess.StartInfo = oStartInfo
        oProcess.Start()

        Dim sOutput As String
        Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
            sOutput = oStreamReader.ReadToEnd()
        End Using
        Console.WriteLine(sOutput)
Run Code Online (Sandbox Code Playgroud)

要获得标准错误:

'Add this next to standard output redirect
 oStartInfo.RedirectStandardError = True

'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
        sOutput = oStreamReader.ReadToEnd()
End Using
Run Code Online (Sandbox Code Playgroud)


Mar*_*rkJ 9

只需将输出传输到文本文件?

MyCommand > "c:\file.txt"
Run Code Online (Sandbox Code Playgroud)

然后读取文件.

  • 实际上,我确实在昨晚读到这个之前就找到了解决方案并且它非常接近.我会使用>>而不是因为我想每次追加结果,但无论如何,谢谢你. (3认同)
  • 我忘了提及,如果您还想捕获文件中的*错误*报告,您应该考虑 `MyCommand > "c:\file.txt 2>&1`。默认情况下,错误输出不包含在文件中。 (2认同)