C#调用EXE文件实现传参和获取返回结果

在项目开发的过程中,不可避免的遇到这种情况:主程序由于算法的第三方库使用的目标平台需为X86的,但是在调用别家公司的程序或者是其他程序驱动不能为X86的(使用x64或者Any cup的没问题)。

我遇到的连接oracle数据库报异常“尝试加载Oracle客户端库时引BadImageFormatException。如果在安装32位Oracle客户端组件的情况下以64位模式运行将出此问题”。这就不由的抱怨一句oracle数据库真的是事多呀,一大堆的问题。

出现这种情况该怎么做呢,两边的平台要求是不一样的,不能修改。

第一种方法:使用其他的不用区分目标平台的库进行连接;

第二种方法:编写一个exe程序,其对接的操作都在这个程序中实现,并由主程序调用。

下面我们就来说一下第二种方法的实现。

1、新建一个“控制台应用程序”-- 在项目启动类文件Program中Main()函数中接收传递来的参数;代码如下:

public class Program
{
  public static void Main(string[] args)
  {
      if(args.Length > 0 && !string.IsNullOrEmpty(args[0]))
      {
          string num = args[0];//获取传递过来的参数
          //DSCommuncationInfo 自定义的类;GetOracleData:连接Oracle数据库和获取数据函数
          DSCommuncationInfo info = GetOracleData(num);
          if (info != null)
          {
              //序列化成字符串数组
              string result = SerializedXMLHelper.Serializer(info);
              //将指定的字符串值(后跟当前行终止符)写入标准输出流。
              Console.WriteLine(result);
          }
      }
  }
}

2、主程序调用exe时,使用进程的方式把exe启动,调用代码如下:

public void StartExternalProgram(string examinerNo)
{
  //这里在dll程序中调用exe,路径是获取dll所在路径
  string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  string exeName = "CterHisExe.exe";
  string fileName = Path.Combine(exePath, exeName);
  //使用进程
  Process myProcess = new Process();
  myProcess.StartInfo.UseShellExecute = false;
  myProcess.StartInfo.RedirectStandardOutput = true;
  myProcess.StartInfo.FileName = fileName;
  myProcess.StartInfo.CreateNoWindow = true;
  //传参,参数以空格分隔,如果某个参数为空,可以传入“”
  myProcess.StartInfo.Arguments = examinerNo;
  p.StartInfo.WorkingDirectory = exePath;//设置要启动的进程的初始目录
  myProcess.Start();//启动
  myProcess.WaitForExit(15000);//等待exe程序处理完,超时15秒
  string xmldata = myProcess.StandardOutput.ReadToEnd();//读取exe中内存流数据
  if (!string.IsNullOrEmpty(xmldata))
  {
      //自己实现的序列化
      var info = SerializedXMLHelper.Deserializer(xmldata);
  }
}

虽然这种方法比较复杂,但是也是解决平台不兼容的可行方法之一。

Process.Start()无法启动exe程序的问题:

1、可能是参数不是绝对路径,exe的路径地址不正确。
2、如果在外部直接运行exe程序没有问题,而当这个程序中有配置文件,或在启动的时候需要读取其他文件时,需要设置StartInfo的WorkingDirectory属性为应用程序的目录。

关于C#调用EXE文件实现传参和获取返回结果的文章就介绍至此,更多相关C#调用EXE文件内容请搜索编程宝库以前的文章,希望以后支持编程宝库

 实践过程效果代码public partial class Form1 : Form{ public Form1() { InitializeComponent(); } Russia ...