编写可执行程序,其它程序调用,并返回数据,C#

有时候在创建临时文件或文件夹,使用完成后,释放失败,删除提示占用,又不能结束主程序,就可以通过别的方法来解决

比如,另外创建一个程序,单独执行任务,完成后结束程序,并返回执行结果,上述问题就能解决。

一、创建需要调用的程序

新建一个Winform窗体

一般主函数是这样的

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Windows.Forms;
 4 
 5 namespace Test
 6 {
 7     static class Program
 8     {
 9         /// <summary>
10         /// 应用程序的主入口点。
11         /// </summary>
12         [STAThread]
13         static void Main()
14         {
15             Application.EnableVisualStyles();
16             Application.SetCompatibleTextRenderingDefault(false);
17             Application.Run(new Form1());
18         }
19     }
20 }

还包含一个Form1。

将启动窗体的代码删掉,Form1删除,给Main函数加上参数。

 1 /// <summary>
 2 /// 应用程序的主入口点。
 3 /// </summary>
 4 [STAThread]
 5 static int Main(string[] args)
 6 { 
 7     int i = 0;
 8     if (args != null)
 9     {
10         #region 逻辑代码
11 
12         #endregion
13     }
14     return i;
15 }
View Code

其中,i为返回的值。

 

二、在主程序中调用上述程序

将生成的Test.exe添加到主程序的资源中

在代码调用方法如下

 1 int result = 0;
 2 Process myProcess = new Process();
 3 try
 4 {
 5     string fileName = Path.Combine(Business.Datas.TempDirectory, "Test.exe");
 6     if (!File.Exists(fileName))
 7     {
 8         byte[] bytes = global::HuaXing.ExamOperation.WindowsManager.Properties.Resources.Text;
 9         File.WriteAllBytes(fileName, bytes);
10     }
11     string para = parms; //parms的格式为 "参数1 参数2 参数3",每个参数之间用空格分隔,参数中有空格可以用""将参数括起来 
12     ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(fileName, para);
13     myProcess.StartInfo = myProcessStartInfo;
14     myProcess.Start();
15     while (!myProcess.HasExited)
16     {
17         myProcess.WaitForExit();
18     }
19     result = myProcess.ExitCode;
20 }
21 catch (Exception ex)
22 {
23     Logger.LogInfo(ex);
24 }

其中result为返回的参数。

 

此方法可以用来临时解决很多棘手的问题。

posted on 2017-01-22 10:25  云栾  阅读(965)  评论(0编辑  收藏  举报