【发布时间】:2012-02-07 05:08:17
【问题描述】:
我有一个调用 Shell 函数的 VB.net 程序。我想在文件中获取从此代码生成的文本输出。但是,这不是执行代码的返回值,所以我真的不知道该怎么做。
该程序是一项服务,但可以访问磁盘没有问题,因为我已经记录了其他信息。整个服务有多个线程,所以我还必须确保在写入文件时它还没有被访问过。
【问题讨论】:
我有一个调用 Shell 函数的 VB.net 程序。我想在文件中获取从此代码生成的文本输出。但是,这不是执行代码的返回值,所以我真的不知道该怎么做。
该程序是一项服务,但可以访问磁盘没有问题,因为我已经记录了其他信息。整个服务有多个线程,所以我还必须确保在写入文件时它还没有被访问过。
【问题讨论】:
您将无法捕获 Shell 的输出。
您需要将其更改为进程,并且需要从该进程中捕获Standard Output(可能还有错误)流。
这是一个例子:
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)
获取标准错误:
'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
【讨论】:
只需将输出通过管道传输到文本文件?
MyCommand > "c:\file.txt"
然后读取文件。
【讨论】:
MyCommand > "c:\file.txt 2>&1。默认情况下,错误输出不包含在文件中。
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
================================================ ========================= 分两行创建一个批处理文件,如下所示:
echo off
ipconfig
' 确保将此批处理文件保存为 ipconfig.bat 或您决定选择的任何名称,但请确保您将点 bat 放在它的末尾。
【讨论】: