.net 中,使用c# 语言 ,执行exe程序。

最近在操作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+"\r\n");
                });
                p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
                {
                    sbOut.Append(e.Data + "\r\n");
                });

                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/vir56k/p/2799810.html