如何获得流程的输出?

时间:2012-09-25 13:35:54

标签: c# stdout

我使用命令行打开WireShark并开始捕获数据包,当我使用CMD窗口时,我可以看到传入数据包的数量和我希望在我的申请表中显示的这个数字(win form),目前这个是我的代码,但我的应用程序崩溃错误

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...  
}

1 个答案:

答案 0 :(得分: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();
        }