C# 执行外部程序

internal class ExternalProgram
{
    public int pid = -1;
    /*
        * 执行程序
        * fileName:要执行的文件名或全路径
        * args 要传递的参数
        */
    public static string run(string fileName,string args)
    {

        return new ExternalProgram().runAndPid(fileName, args);
    }

    /*
        * 执行程序,并且可以返回pid,但要在异步情况下才能获取pid
        * fileName:要执行的文件名或全路径
        * args 要传递的参数
        */
    public string runAndPid(string fileName, string args)
    {

        using (Process p = new Process())
        {
            p.StartInfo.FileName = fileName; // 要执行的文件名
            p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
            p.StartInfo.CreateNoWindow = true; //不显示程序窗口
            p.StartInfo.Arguments = args; // 传递的参数
            p.StartInfo.WorkingDirectory = "."; // 指定工作路径
            // 返回字符串编码为utf-8
            p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            p.Start();//启动程序
            pid = p.Id;
            p.StandardInput.AutoFlush = true;
            //获取cmd窗口的输出信息
            string output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            return output;
        }
    }
}