在Unity3d中调用外部程序及批处理文件

如果调用外部普通应用程序, 比如notepad.exe 这样调用

 1 static public bool ExecuteProgram(string exeFilename, string workDir, string args)  
 2 {  
 3     System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();  
 4     info.FileName = exeFilename;  
 5     info.WorkingDirectory = workDir;  
 6     info.RedirectStandardOutput = true;  
 7     info.RedirectStandardError = true;  
 8     info.Arguments = args;  
 9     info.UseShellExecute = false;  
10     info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;  
11   
12     System.Diagnostics.Process task = null;  
13   
14     bool rt = true;  
15   
16     try  
17     {  
18         task = System.Diagnostics.Process.Start(info);  
19         if (task != null)  
20         {  
21             task.WaitForExit(10000);  
22         }   
23         else  
24         {  
25             return false;  
26         }  
27     }   
28     catch (Exception e)  
29     {  
30         Debug.LogError("Error: " + e.ToString());  
31         return false;  
32     }   
33     finally  
34     {  
35         if (task != null && task.HasExited)  
36         {  
37             string output = task.StandardError.ReadToEnd();  
38             if (output.Length > 0)  
39             {  
40                 Debug.LogError(output);  
41             }  
42               
43             output = task.StandardOutput.ReadToEnd();  
44             if (output.Length > 0)  
45             {  
46                 Debug.Log("Error: " + output);  
47             }  
48               
49             rt = (task.ExitCode == 0);  
50         }  
51     }  
52   
53     return rt;  
54 }  

如果需要调用Window的批处理文件BAT, 

或者含有控制台输出的程序, 

或者使用上面的方法卡死, 则使用下面的方法运行

 1 static bool ExecuteProgram(string exeFilename, string workDir, string args)  
 2 {  
 3     System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();  
 4     info.FileName = exeFilename;  
 5     info.WorkingDirectory = workDir;  
 6     info.UseShellExecute = true;  
 7     info.Arguments = args;  
 8     info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;  
 9   
10     System.Diagnostics.Process task = null;  
11     bool rt = true;  
12     try  
13     {  
14         Debug.Log("ExecuteProgram:" + args);  
15           
16         task = System.Diagnostics.Process.Start(info);  
17         if (task != null)  
18         {  
19             task.WaitForExit(100000);  
20         }  
21         else  
22         {  
23             return false;  
24         }  
25     }  
26     catch (Exception e)  
27     {  
28         Debug.LogError("ExecuteProgram:" + e.ToString());  
29         return false;  
30     }   
31     finally  
32     {  
33         if (task != null && task.HasExited)  
34         {  
35             rt = (task.ExitCode == 0);  
36         }  
37     }  
38   
39     return rt;  
40 }  
原文地址:https://www.cnblogs.com/AaronBlogs/p/7839555.html