2012-09-25 54 views
1

我打開WireShark使用命令行並開始捕獲數據包,當我使用CMD窗口時,我可以看到傳入數據包的數量和這個數字,我想在我的申請表中顯示(勝利形式),目前這是我的代碼,但有錯誤我的應用程序崩潰如何獲取進程的輸出?

static void Main(string[] args) 
{ 
    try 
    { 
     string _pcapPath = @"C:\test.pcap"; 
     Process _tsharkProcess = new Process(); 
     _tsharkProcess.StartInfo.FileName = @"C:\Program Files\Wireshark\tshark.exe"; 
     _tsharkProcess.StartInfo.Arguments = string.Format(" -i " + 2 + " -c " + int.MaxValue + " -w " + _pcapPath); 
     _tsharkProcess.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived); 
     _tsharkProcess.StartInfo.RedirectStandardOutput = true; 
     _tsharkProcess.StartInfo.UseShellExecute = false; 
     //_tsharkProcess.StartInfo.CreateNoWindow = true; 
     //_tsharkProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 
     _tsharkProcess.Start(); 
     StreamReader myStreamReader = _tsharkProcess.StandardOutput; 
     string myString = myStreamReader.ReadLine(); //read the standard output of the spawned process. 
     Console.WriteLine(myString); 
     _tsharkProcess.WaitForExit(); 
    } 
    catch (Exception) 
    { 

    } 

} 

private static void process_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    string srt = e.Data; //arg.Data contains the output data from the process... 
} 
+0

所以張貼錯誤因果http://stackoverflow.com/questions/1700695/getting-output-from-one-executable-in-an-other-one –

+2

你有沒有嘗試之前設置'RedirectStandardOutput'調用'process.Start()'? –

+0

現在好了在process.Start()之前設置RedirectStandardOutput和UseShellExecute後就可以了,但是如何獲取我的過程的輸出?現在打開的CMD窗口爲空 –

回答

2

您可以使用此代碼

諾塔嘗試:將這些行之前開始

  process.StartInfo.RedirectStandardOutput = true; 
      process.StartInfo.UseShellExecute = false; 
      process.Start(); 

代碼:

  Process process = new Process(); 
      process.StartInfo.FileName = @"C:\Program Files\Wireshark\tshark.exe"; 
      process.StartInfo.Arguments = string.Format(" -i " + _interfaceNumber + " -c " + int.MaxValue + " -w " + _pcapPath); 
      process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived); 

      process.StartInfo.RedirectStandardOutput = true; 
      process.StartInfo.UseShellExecute = false; 


     process.Start(); 

      StreamReader myStreamReader = process.StandardOutput; 
      // Read the standard output of the spawned process. 
      string myString = myStreamReader.ReadLine(); 
      Console.WriteLine(myString); 

      process.WaitForExit(); 
      process.Close(); 
     } 
+0

我無法到達行字符串myString = myStreamReader.ReadLine();即使在創建斷點後,似乎在process.Start()之後;它全部卡住了(但是進程正在工作,並且在磁盤上創建帶有數據包的文件) –

+0

您可能需要稍等片刻才能執行處理 –

+0

您的意思是thread.Sleep after process.start? –

相關問題