C#/.Net调用控制台程序并获得返回结果

使用C#/.Net调用控制台程序并获得返回结果主要是可以实现托管代码调用非托管代码过程中,非托管代码内存泄露(无源代码,无法修改)导致的主程序奔溃,而控制台程序则可以针对非托管代码再次封装,处理内存泄露异常。

注意在控制台程序中,需要使用:

 SetErrorMode(((SetErrorMode(ErrorModes.SYSTEM_DEFAULT) | ErrorModes.SEM_NOGPFAULTERRORBOX) | ErrorModes.SEM_FAILCRITICALERRORS) | ErrorModes.SEM_NOOPENFILEERRORBOX);

来实现系统错误提示的屏蔽,如:XXXX模块内存读取失败,程序即将关闭...详见:《.NET通过 P/Invoke调用win32 dll的一个实际例子》

           

首先明确调用者与被调用者是在两个不同的进程中,返回结果使用委托代理来获取。主要代码如下:

            string strConsoleRoot = System.Configuration.ConfigurationManager.AppSettings["ConsoleRoot"];

            string strConsolePath = strConsoleRoot + @"\FingerMatchSingle.exe";

            string strVerTemplate = listStudent.First()["CardNo"].ToString(); 

            string strFingerTemplate1 = "\"" + strCardNumber  + "\"";

            string strFingerTemplate2 = "\"" + strVerTemplate + "\"";

              ProcessStartInfo start = new ProcessStartInfo();

            start.Arguments = strConsolePath + " " + strFingerTemplate1 + " " + strFingerTemplate2;

            start.WorkingDirectory = strConsoleRoot;

            start.FileName = strConsolePath;

            start.UseShellExecute = false;

            start.RedirectStandardInput = true;

            start.RedirectStandardOutput = true;

            start.RedirectStandardError = true;

            start.CreateNoWindow = true;

            process = Process.Start(start);

            process.OutputDataReceived += (sender, e) =>

            {

                if (!string.IsNullOrEmpty(e.Data))

                { 

                }

                else

                { 

                            //控制台程序异常后的代码

                }

                process.CancelOutputRead();

                process.Close();

                process.Dispose();

            };

            process.BeginOutputReadLine();

其中控制台程序代码,请见《.NET通过 P/Invoke调用win32 dll的一个实际例子》

猜你喜欢

转载自blog.csdn.net/bruce135lee/article/details/81180589
今日推荐