Dana Yeger
Dana Yeger

Reputation: 645

How to get the output of a process?

I am open WireShark using command line and start capture the packets, when i do it using CMD windows i can see the number of the incoming packets and this number i want to show in my application form (win form), currently this is my code but my application crash with error

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

Upvotes: 1

Views: 1799

Answers (1)

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with this code

Nota : Set these lines before start

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

Code:

            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();
        }

Upvotes: 2

Related Questions