.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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值