(转)C#执行exe程序

    本文转自:http://www.cnblogs.com/vir56k/archive/2012/12/03/2799810.html,作者张云飞VIR

    最近在操作adb做一些事情,就需要开发个windows引用程序。在这里就需要使用winform来调用adb.exe来做事了。然而,要正确调用,还想要得到调用成功或者的失败的反馈。就需要做点事情了,需要对输出流和异常流进行重定向,其中总是遇到readToEnd方法的假死。查询了一些文档,终于找到一个比较好的实现。代码如下:

复制代码
///<summary>
/// 执行exe
///</summary>
public class ProcessExcuter
{

public static void Run(string exeFilePath, string args, out string res, out string error)
{
if (string.IsNullOrEmpty(exeFilePath) || !System.IO.File.Exists(exeFilePath))
{
throw new System.IO.FileNotFoundException();
}
if (string.IsNullOrEmpty(args))
{
throw new ArgumentException();
}

Process p;
p = new Process();
p.StartInfo.FileName = exeFilePath;
p.StartInfo.Arguments = args;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
int time = 5000;

StringBuilder sbOut = new StringBuilder();
StringBuilder sbError = new StringBuilder();

try
{
p.Start();

p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
{
sbError.Append(e.Data+" ");
});
p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
{
sbOut.Append(e.Data + " ");
});

p.BeginErrorReadLine();
p.BeginOutputReadLine();

p.WaitForExit(time);
}
finally
{
if (p != null)
{
p.Close();
p.Dispose();
p = null;
}
}
res = sbOut.ToString().Trim();
error = sbError.ToString().Trim();
} }
复制代码

参考: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginerrorreadline.aspx

原文地址:https://www.cnblogs.com/hhhh2010/p/3666029.html