我正在尝试用参数打开一个隐藏的控制台应用程序,并且基本上将它的输出连续记录到文件中,直到它被停止。
我尝试过使用内存流并将其写入文件,但它似乎确实有用了。现在我正在尝试利用DataRecievedEvent,以便我可以进一步处理输出。现在我没有得到任何输出。
以下是我打开控制台应用程序的方法:
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);
}
答案 0 :(得分:0)
我认为问题在于,您对函数的引用超出了函数capturePackets的范围。您将需要为进程变量提供与writer相同的作用域,或者在capturePackets函数中等待,直到进程使用WaitForExit()方法退出。虽然您创建的进程继续运行,但当对它的引用超出范围(通过流程变量)时,事件将停止处理。