2012-01-10 83 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決定選擇,但要確保ü把點蝙蝠在它的結尾。

相關問題