zoukankan      html  css  js  c++  java
  • .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

  • 相关阅读:
    thinkPHP入门之二
    thinkPHP入门
    斐波那契数列,冒泡排序,选择排序,数组去重
    jquery-懒加载插件
    本地存储之cookie
    javascript的快速排序法
    [luogu2165 AHOI2009] 飞行棋 (枚举)
    [luogu2576 SCOI2010] 幸运数字 (容斥原理)
    [luogu2587 ZJOI2008] 泡泡堂 (贪心)
    [luogu2602 ZJOI2010] 数字计数 (数位dp)
  • 原文地址:https://www.cnblogs.com/vir56k/p/2799810.html
Copyright © 2011-2022 走看看