Process.Start启动exe
同步执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
static void runCommand() { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c DIR"; // 执行DIR命令 process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); //输出所有执行结果 string output = process.StandardOutput.ReadToEnd(); Console.WriteLine(output); //输出所有错误信息 string err = process.StandardError.ReadToEnd(); Console.WriteLine(err); process.WaitForExit(); } |
异步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
static void runCommand() { //* Create your Process Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c DIR"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; //注册输出结果事件 process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler); //执行进程 process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { //* Do your stuff with the output (write to console/log/StringBuilder) Console.WriteLine(outLine.Data); } //输出事件注册也可以这么写 process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data); |
如果您对C#游戏开发感兴趣,可以扫下面二维码加入我们的QQ群来一起学习交流
原创文章,转载请注明本文链接地址(违者必究):Process.Start启动exe