代码改变世界

C# 通过一个控制台打开另一个控制台

2017-12-17 21:39  taozsay  阅读(2655)  评论(0编辑  收藏  举报

现有个需求是通过一个主程序获取配置的线程数和进程数打开连一个控制台程序,将线程数和系统编码作为参数传给控制台程序。

下面附上Demo。

 1 private static void Main(string[] args)
 2         {
 3             var arg = new string[2];
 4             arg[0] = "5";//线程数
 5             arg[1] = "SystemCode";//系统编码
 6 
 7             //打开指定目录地址
 8             //StartProcess(@"E:\Demo\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe", arg);
 9 
10             for (int i = 1; i < 2; i++)
11             {
12                 Console.WriteLine("123");
13                 StartProcess("ConsoleApplication1.exe", arg);
14             }
15         }
16 
17         public static bool StartProcess(string filename, string[] args)
18         {
19             try
20             {
21                 string s = "";
22                 foreach (string arg in args)
23                 {
24                     s = s + arg + " ";
25                 }
26                 s = s.Trim();
27                 var myprocess = new Process();
28                 var startInfo = new ProcessStartInfo(filename, s);
29                 myprocess.StartInfo = startInfo;
30                 //通过以下参数可以控制exe的启动方式,具体参照 myprocess.StartInfo.下面的参数,如以无界面方式启动exe等
31                 //myprocess.StartInfo.UseShellExecute = true;
32                 myprocess.Start();
33                 return true;
34             }
35             catch (Exception ex)
36             {
37                 Console.WriteLine("启动应用程序时出错!原因:" + ex.Message);
38             }
39             return false;
40         }