【Unity】在Unity中使用C#执行外部文件,如.exe或者.bat

示例代码

            var process = ExecuteFile(workPath, exePath);
            if (process.Start())
            {
    
    
                Debug.Log(ReadToEnd(process.StandardOutput));
            }

            Debug.LogError(ReadToEnd(process.StandardError));

工具代码

		public static string ReadToEnd(StreamReader reader)
        {
            var sbd = new StringBuilder();
            while (true)
            {
                var readLine = reader.ReadLine();
                if (readLine == null)
                {
                    break;
                }

                sbd.AppendLine(readLine);
            }
            return sbd.ToString();
        }

        public static Process ExecuteFile(string workDir, string executeFile)
        {
            var process = new Process();
            var startInfo = new ProcessStartInfo(executeFile)
            {
                WorkingDirectory = workDir,
                CreateNoWindow = false,
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                StandardOutputEncoding = Encoding.GetEncoding("GB2312"),
                StandardErrorEncoding = Encoding.GetEncoding("GB2312"),
            };
            process.StartInfo = startInfo;
            return process;
        }

猜你喜欢

转载自blog.csdn.net/ak47007tiger/article/details/125368556
今日推荐