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

 

//在需要的程序中调用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();
}
}

posted @ 2014-08-10 11:01  桔子柠檬  阅读(391)  评论(0编辑  收藏  举报