在程序中若要调用外部程序,可以通过引入System.Diagnostics命名空间。这里以调用.bat批处理文件或者dos命令为例。
一、调用dos命令
需添加的命名空间:
using System.Diagnostics;
using System.IO;
using System.IO;
- public string Call(string command, int seconds)
- {
- string output = ""; //输出字符串
- if (command != null && !command.Equals(""))
- {
- ProcessStartInfo startInfo = new ProcessStartInfo();
- startInfo.FileName = "cmd.exe";//设定需要调用的外部程序
- startInfo.Arguments = "/C " + command;//所需参数,“/C”表示执行完命令后马上退出
- startInfo.UseShellExecute = false;//不使用系统外壳程序启动
- startInfo.RedirectStandardInput = false;//不重定向输入
- startInfo.RedirectStandardOutput = true; //重定向输出
- startInfo.CreateNoWindow = true;//不创建窗口
-
- Process process = new Process();//创建进程对象
- process.StartInfo = startInfo;
- try
- {
- if (process.Start())//开始进程
- {
- if (seconds == 0)
- {
- process.WaitForExit();//这里无限等待进程结束
- }
- else
- {
- process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
- }
- }
- if(process.HasExited)
- {
- StreamReader myOutput = process.StandardOutput;
- output = myOutput.ReadToEnd();//读取整个输出
- //output = myOutput.ReadLine();//读取一行输出。此外还有读取特定字节的输出。
- }
- }
- catch
- {
- }
- finally
- {
- if (process != null)
- process.Close();
- }
- }
- return output;
- }
二、调用批处理
调用批处理很简单,直接:
startInfo.FileName = "xxx.bat";//设定需要调用的外部程序
不需要startInfo.Arguments。
另外,如果不需要获得输出,
startInfo.RedirectStandardOutput = false
;
//重定向输出
后面的输出代码也不需要即可。
参考博客:
http://www.cnblogs.com/huangqing/articles/2232985.html
http://www.bolg.csdn.net/zhongjiekangping/article/details/5261648