c#中windows服务执行Process获取不了返回值,求高手指点
首先说明,是c# windows 服务,不是应用程序winform
下面代码在winform中运行正常能获取当前所有的netstat信息返回值,而在Windows Service中则获取不到strLine的信息。
- C# code
protected override void OnStart(string[] args) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); //查看本机端口占用情况 p.StandardInput.WriteLine("netstat -an"); p.StandardInput.WriteLine("exit"); // StreamReader reader = p.StandardOutput;//截取输出流 string strLine = reader.ReadLine();//每次读取一行 while (!reader.EndOfStream) { strLine = reader.ReadLine();//再下一行 } p.WaitForExit();//等待程序执行完退出进程 p.Close();//关闭进程 reader.Close();//关闭流 [color=#FF0000]这里strLine获取到的信息只有一句C:\WINDOWS\system32>exit[/color]}
[解决办法]
执行netstat -ano >> C:\info.txt
然后分析info.txt文件