c#中执行dos命令

在程序中若要调用外部程序,可以通过引入System.Diagnostics命名空间。这里以调用.bat批处理文件或者dos命令为例。
一、调用dos命令
需添加的命名空间:
using System.Diagnostics;
using System.IO;

  1.         public string Call(string command, int seconds)  
  2.         {  
  3.             string output = ""//输出字符串  
  4.             if (command != null && !command.Equals(""))  
  5.             {  
  6.                   
  7.                 ProcessStartInfo startInfo = new ProcessStartInfo();  
  8.                 startInfo.FileName = "cmd.exe";//设定需要调用的外部程序 
  9.                 startInfo.Arguments = "/C " + command;//所需参数,“/C”表示执行完命令后马上退出  
  10.                 startInfo.UseShellExecute = false;//不使用系统外壳程序启动  
  11.                 startInfo.RedirectStandardInput = false;//不重定向输入  
  12.                 startInfo.RedirectStandardOutput = true//重定向输出  
  13.                 startInfo.CreateNoWindow = true;//不创建窗口

  14.                 Process process = new Process();//创建进程对象
  15.                 process.StartInfo = startInfo;  
  16.                 try  
  17.                 {  
  18.                     if (process.Start())//开始进程  
  19.                     {  
  20.                         if (seconds == 0)  
  21.                         {  
  22.                             process.WaitForExit();//这里无限等待进程结束  
  23.                         }  
  24.                         else  
  25.                         {  
  26.                             process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒  
  27.                         } 
  28.                     }  
  29.                     if(process.HasExited)
  30.                     {
  31.                         StreamReader myOutput = process.StandardOutput;
  32.                         output = myOutput.ReadToEnd();//读取整个输出
  33.                       //output = myOutput.ReadLine();//读取一行输出。此外还有读取特定字节的输出。
  34.                     }
  35.                 }  
  36.                 catch  
  37.                 {  
  38.                 }  
  39.                 finally  
  40.                 {  
  41.                     if (process != null)  
  42.                         process.Close();  
  43.                 }  
  44.             }  
  45.             return output;  
  46.         }  

二、调用批处理
调用批处理很简单,直接:
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
更多 1


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值