C#调用cmd执行命令获取返回值
本文以bat批量处理文件做的,在处理过程中动态显示出来每条命令执行的结果,采用的是读取每行命令,调用cmd执行,获取返回值,此方法不是唯一方法
using System;
using System.Diagnostics;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
//@"F:lockly-du est_for_BATDu.BAT"
//打开BAT
StreamReader sr = new StreamReader(@"F:lockly-du est_for_BATDu.BAT");
string line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
//cmd(line);
Console.WriteLine(cmd(line));
}
return;
}
static string cmd(string sr)
{
Process pro = null;
string ll = string.Empty;
try
{
pro = new Process();
pro.StartInfo.FileName = "cmd.exe"; //cmd
pro.StartInfo.UseShellExecute = false; //不显示shell
pro.StartInfo.CreateNoWindow = true; //不创建窗口
pro.StartInfo.RedirectStandardInput = true; //打开流输入
pro.StartInfo.RedirectStandardOutput = true; //打开流输出
pro.StartInfo.RedirectStandardError = true; //打开错误流
pro.Start();//执行
pro.StandardInput.WriteLine(sr + "&exit"); //&exit运行完立即退出
pro.StandardInput.AutoFlush = true; //清缓存
ll = pro.StandardOutput.ReadToEnd(); //读取输出
pro.WaitForExit(); //等待程序执行完退出进程
pro.Close();//结束
return ll;
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
return null;
}
}
}
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了
