在程序中使用命令打开一个进程和记录该进程执行日志

 

//在需要的程序中调用ExcutedCmd函数来打开执行dos命令 

//cmd 命令  args 命令参数
private static void ExcutedCmd(string cmd, string args)
{
using (Process p = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
p.EnableRaisingEvents = true;
p.ErrorDataReceived += new DataReceivedEventHandler(process_ErrorDataReceived);
p.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
p.Exited += new EventHandler(process_Exited);
p.StartInfo = psi;

p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();

}
}

//获取进程执行的错误信息
static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
WriteLog(e.Data);
}

 

//获取进程执行的输出信息

static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
 WriteLog(DateTime.Now.ToString("yy-MM-dd hh:mm:ss") + "输出数据!"+e.Data);
}

 

//进程结束事情处理

static void process_Exited(object sender, EventArgs e)
{

WriteLog(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + "本次执行结束!");
}

 

//将流写入文档中

static void WriteLog(string str)
{
using (StreamWriter sw = File.AppendText(@"d:\convertLog.txt"))
{
sw.WriteLine(str);
sw.Flush();
}
}

转载于:https://www.cnblogs.com/orangeLemon/p/ExcutedCmd.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值