2012-01-10 77 views
13

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

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

回答

24

您将无法捕获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) 
+3

哇,对于这样一个小小的壮举来说这很复杂...... – 2012-01-11 13:25:02

6

只需将输出管道输出到文本文件?

MyCommand > "c:\file.txt" 

然后阅读文件。

+2

事实上,我昨天晚上在阅读本文之前发现了这个解决方案,并且它非常接近。我会用>>代替,因为我想每次追加结果,但无论如何都要感谢你。 – 2012-01-11 13:24:22

+1

我忘了提,你应该考虑'mycommand的>“C:\ file.txt的2>&1',如果你也想捕捉*错误*文件中报告默认情况下,错误输出不包含在文件中 – MarkJ 2012-01-11 16:04:26

+0

到。匿名downvoter:护理发表评论 – MarkJ 2012-08-14 15:34:27

0
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)) 对于每个LN作为字符串在输出 RichTextBox1.AppendText(LN & vbNewLine) lstScan.Items.Add(LN & vbNewLine ) 接着

=========================================== ============================ 创建一个如下图所示在两行批处理文件:

呼应关闭

IPCONFIG

“确保你这个批处理文件保存为ipconfig.bat或任何名u决定选择,但要确保ü把点蝙蝠在它的结尾。