【C#】调用可执行程序exe进程返回处理结果

  1. 请看一个例子,假设用户点击了一个按钮,去执行cmd命令adb devices得到连接设备信息,代码如下
private void button1_Click(object sender, EventArgs e)
{
	//可执行文件名,例如 D://adb.exe
    var exe = label1.Text;
    button1.Enabled = false;
	//方法1
    callProcess(exe, "devices", delegate (String msg)
    {
        richTextBox1.Text += msg;
    });

    //方法2
    //String res = callProcess(exe, "devices");
    //richTextBox1.Text = res;

    button1.Enabled = true;
}
  1. 方法1, 异步调用方法实现
/// 
/// 异步方式 调用可执行exe程序
/// 
/// exe文件名
/// 传参
/// 调用后返回结果
private void callProcess(string fileName, string Arguments, Action<string> onReceive)
{
    var p = new Process();

    // 设置属性
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.FileName = fileName;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
    {
        if (String.IsNullOrEmpty(e.Data)) return;
        //泛型委托 匿名方法
        this.BeginInvoke(onReceive, e.Data);
    };

    p.StartInfo.Arguments = Arguments;
    p.Start();

    p.BeginOutputReadLine();
}
  1. 方法2, 同步调用方法实现
/// 
/// 同步方式 调用可执行exe程序
/// 
/// exe文件名
/// 传参
/// 返回调用后结果
private string callProcess(string fileName, string arguments)
{
    var psi = new ProcessStartInfo(fileName, arguments);
    psi.UseShellExecute = false;
    psi.CreateNoWindow = true;
    psi.RedirectStandardError = true;
    psi.RedirectStandardInput = true;
    psi.RedirectStandardOutput = true;

    var pes = Process.Start(psi);

    var sbuffer = new StringBuilder();
    var sout = pes.StandardOutput;
    while (!sout.EndOfStream)
    {
        var line = sout.ReadLine();
        if (String.IsNullOrEmpty(line)) continue;
        sbuffer.AppendLine(line);
    }
    pes.WaitForExit();
    pes.Close();
    String res = sbuffer.ToString();
    sbuffer.Clear();
    return res;
}
  1. 调用可执行程序exe的方法就这两种了,到此结束!

小提示:

  • 若运行报错 StandardOut 未重定向或者该进程尚未启动
  • 就加上 RedirectStandardOutput = true;即可解决

你可能感兴趣的:(C#,c#)