代码
#if UNITY_EDITOR using System.Collections.Generic; using System.IO; using System.Text; using UnityEditor; using UnityEngine; public class CmdTool { private static Queue<string> _cmdQueue = new Queue<string>(); [MenuItem("MyTools/ShowJavaVersion", false)] static void ShowJavaVersion() { _cmdQueue.Enqueue("java -version"); CheckAndRunCmd(); } private static void CheckAndRunCmd() { if (_cmdQueue.Count <= 0) { Debug.Log("finish"); return; } using (var process = new System.Diagnostics.Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.WorkingDirectory = @"C:\"; //不设置就是当前目录 process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; process.StartInfo.CreateNoWindow = true; //不显示命令行的黑窗口 process.Start(); //启动程序 var cmd = _cmdQueue.Dequeue(); //process.StandardInput.AutoFlush = true; //下面手动Flush了, 所以这边可以注释掉 process.StandardInput.WriteLine(cmd); //执行命令 process.StandardInput.WriteLine("exit"); //执行完后自动退出cmd process.StandardInput.Flush(); //或 process.StandardInput.Close(); process.WaitForExit(); //等待程序执行完退出进程 if (process.HasExited) { PrintAllLines(process.StandardOutput); PrintAllLines(process.StandardError); CheckAndRunCmd(); } } } private static void PrintAllLines(StreamReader sr) { var gbkEnc = Encoding.GetEncoding("gb2312"); //windows的命令行默认是gbk字符集的 using (StreamReader sr2 = new StreamReader(sr.BaseStream, gbkEnc)) //换成gbk的Reader来读 { while (!sr2.EndOfStream) { string curLine = sr2.ReadLine(); if (!string.IsNullOrEmpty(curLine)) { Debug.Log($"{curLine}"); } } } } } #endif
执行ShowJavaVersion的运行结果:
参考
C#:为什么我的Process运行Java.exe工作正常,但窗口没有返回任何输出? - VoidCC
用户对问题“如何在C#中逐行读取命令输出结果”的回答 - 问答 - 腾讯云开发者社区-腾讯云 (tencent.com)
C#/.NET 中启动进程时所使用的 UseShellExecute 设置为 true 和 false 分别代表什么意思?_walter lv的博客-CSDN博客_useshellexecute
ImageMagick 的安装及使用 - Rogn - 博客园 (cnblogs.com)
标签:执行命令,cmdQueue,System,博客,unity,static,ShowJavaVersion,using From: https://www.cnblogs.com/sailJs/p/16895662.html