简体   繁体   中英

How to continuously output console application to text file in C#

I am trying to open up a hidden console application with arguments, and basically log it's output into a file continuously until it is stopped.

I have tried using a memory stream and writing it into the file, and it did seem to work for a bit. Now I am trying to take advantage of the DataRecievedEvent so I can further process the output. Right now I am not getting any output.

Here is how I am opening the console application:

StreamWriter writer = new StreamWriter("tsharkfieldoutput.txt", true)

private void capturePackets(int device)
        {

           string path =
                string.Format("-i " + device +
                              "  -O SNMP -T fields -e snmp.value.oid -e snmp.VarBind -e snmp.variable_bindings -e snmp.value.octets -e snmp.name -R udp src " +
                              destPort);
           string tshark = @"C:\Program Files\Wireshark\tshark.exe";
           ProcessStartInfo ps = new ProcessStartInfo();
           ps.FileName = tshark;
           ps.CreateNoWindow = true;
           ps.WindowStyle = ProcessWindowStyle.Hidden;
           ps.UseShellExecute = false;
           ps.CreateNoWindow = true;
           ps.RedirectStandardOutput = true;
           ps.Arguments = path;
           Process process = new Process();
           process.StartInfo = ps;
           process.Start();
           process.OutputDataReceived += new DataReceivedEventHandler(tshark_OutputDataReceived);
            //Not using stream reader any more.
           //StreamReader myStreamReader = process.StandardOutput;
            writer.Write("Begin tshark output- " + DateTime.Now + " - " + Environment.NewLine);

        }

        private void tshark_OutputDataReceived(object sender, DataReceivedEventArgs arg)
        {
            string tsharkline = arg.Data; //arg.Data contains the output data from the process...        

                writer.Write(tsharkline);

        }

I think the issue is that your reference to the process is going out of scope at the end of function capturePackets. You will either need to give the process variable the same scope as the writer or wait in the capturePackets function until the process exits using the WaitForExit() method. Although the process that you create continues to run, when the reference to it goes out of scope (via the process variable), the events will stop being processed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM