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

  • 相关阅读:
    vue动态绑定class的几种方式
    寒假阅读笔记之《人月神话》
    人月神话阅读笔记1
    寒假阅读笔记之《构建之法》2
    寒假阅读笔记之《构建之法》
    家庭记账本APP(7)
    家庭记账本APP(6)
    家庭记账本APP(5)
    家庭记账本APP(4)
    家庭记账本APP(3)
  • 原文地址:https://www.cnblogs.com/hhhh2010/p/3666029.html
Copyright © 2011-2022 走看看