Process.start: how to get the output?
2015-08-06 21:58
676 查看
1: Synchronous example
Note that it's better to process both output and errors: they must be handled separately.
(*) For some commands (here
2: Asynchronous example
If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:
static void runCommand() { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*) process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); //* Read the output (or the error) string output = process.StandardOutput.ReadToEnd(); Console.WriteLine(output); string err = process.StandardError.ReadToEnd(); Console.WriteLine(err); process.WaitForExit(); }
Note that it's better to process both output and errors: they must be handled separately.
(*) For some commands (here
StartInfo.Arguments) you must add the
/cdirective, otherwise the process freezes in the
WaitForExit().
2: Asynchronous example
static void runCommand() { //* Create your Process Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c DIR"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; //* Set your output and error (asynchronous) handlers process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler); //* Start process and handlers process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { //* Do your stuff with the output (write to console/log/StringBuilder) Console.WriteLine(outLine.Data); }
If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:
//* Set your output and error (asynchronous) handlers process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
相关文章推荐
- Yii2中GridView
- php-IIS和WampServer 冲突问题
- 再谈TQ2440使用TFTP下载程序
- php5中的clone 浅拷贝 深拷贝
- ubuntu php安装 curl扩展
- php学习之路:WSDL详细解释(两)
- proftpd+ssl安装及使用
- 概念了解:CGI,FastCGI,PHP-CGI与PHP-FPM 各公共网关接口介绍
- php5中对象赋值机制
- C#通过PHP向MySQL插入数据的编码问题
- php5中虚函数的实现
- php能把函数名作为参数传递吗?
- xhprof(PHP性能分析工具)
- php中经常使用的string函数
- phpstorm开发环境搭建流程
- phpstorm 无法输入中文
- PHP编译过程中常见错误信息的解决方法
- zend 集成svn
- ZH奶酪:LAMP环境中如何重新部署一个Yii2.0 web项目
- [php] thinkphp RBAC解析