[英]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.
现在,我正在尝试利用DataRecievedEvent的优势,以便进一步处理输出。 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. 我认为问题在于您对过程的引用超出了功能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.
您将需要为流程变量赋予与writer相同的作用域,或者在capturePackets函数中等待,直到使用WaitForExit()方法退出流程为止。 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.
尽管您创建的过程继续运行,但是当对其的引用超出范围(通过过程变量)时,事件将停止处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.