question

BigBear avatar image
0 Votes"
BigBear asked ZhiLv-MSFT answered

.Net Core – Process() running an exe console and how to get the data in my app calling

Hello all,
I currently have a .Net Core app that is calling a UPS API. (This API is unsupported by .Net Core that is why I am doing it this way) I have my .Net Core calling the exe and inputting a parameter. All of the correct info displays on the console of this exe. Now I am wanting to retrieve the input that displays in my .Net Core app. I have been unsuccessful so far, im assuming its with DataReceivedEventArgs.
Thank you for your time.
[HttpGet("GetUPSPackage")]
public async Task<IActionResult> GetUPSPackage(string trackingNumber)
{
var x = 3;
using (var process = new Process())
{
try
{
process.StartInfo.FileName = @"TrackWSSample.exe";
process.StartInfo.Arguments = $"{trackingNumber}";

                     process.StartInfo.CreateNoWindow = false;
                     process.StartInfo.UseShellExecute = false;
    
                     process.StartInfo.RedirectStandardOutput = true;
                     process.StartInfo.RedirectStandardError = true;
    
    
                     //process.OutputDataReceived += (sender, data) => _logger.LogInformation(data.Data);
                     process.OutputDataReceived += Process_OutputDataReceived;
    
    
                     process.ErrorDataReceived += (sender, data) => _logger.LogError(data.Data);
                     _logger.LogInformation("Exe Starting..");
    
                     process.Start();
                     process.BeginOutputReadLine();
                     process.BeginErrorReadLine();
    
                     _logger.LogInformation(ShipmentPackage);
    
    
    
                     var exited = process.WaitForExit(1000 * 6);     // (optional) wait up to 6 seconds
                      _logger.LogInformation($"exit {exited}");
    
                     return Ok();
                 }
                 catch (Exception ex) { }
             }
    
 //Here is the .Net Framework console exe
 TrackService track = new TrackService();
                 TrackRequest tr = new TrackRequest();
                 UPSSecurity upss = new UPSSecurity();
                 UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
                 upssSvcAccessToken.AccessLicenseNumber = "theid";
                 upss.ServiceAccessToken = upssSvcAccessToken;
                 UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
                 upssUsrNameToken.Username = "username";
                 upssUsrNameToken.Password = "pass!";
                 upss.UsernameToken = upssUsrNameToken;
                 track.UPSSecurityValue = upss;
                 RequestType request = new RequestType();
                 String[] requestOption = { "15" };
                 request.RequestOption = requestOption;
                 tr.Request = request;
                 tr.InquiryNumber = "1Z5811560241454350";//"1Z648616E192760718";// "990728071";// "1Z12345E0205271688";//"Your track inquiry number";
                 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.
                 TrackResponse trackResponse = track.ProcessTrack(tr);
                 Console.WriteLine("The transaction was a " + trackResponse.Response.ResponseStatus.Description);
                 Console.WriteLine("Shipment Service " + trackResponse.Shipment[0].Service.Description);
                 Console.WriteLine("Shipment Code " + trackResponse.Shipment[0].Service.Code);
dotnet-csharpdotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

Hi @BigBear,

When using the Process() class running the exe console application, you can get the console output after the process has existed.

Please refer the following sample:

Console application:

 namespace HelloWorld
 {
     class Program
     {
         static void Main(string[] args)
         { 
             Console.WriteLine("This is hello word application, the input value is :" + string.Join("_", args));
             Console.WriteLine("The transaction was a " + "DescriptionA");
             Console.WriteLine("Shipment Service " + "DescriptionB");
             Console.WriteLine("Shipment Code " + "Service.Code");
         }
     }
 }

API method:

 [Route("api/[controller]")]
 [ApiController]
 public class ToDoController : ControllerBase
 {
     private readonly IWebHostEnvironment _environment;
     public ToDoController(IWebHostEnvironment environment)
     {
         _environment = environment;
     }
     // GET api/<ToDoController>/5
     [HttpGet("{id}")]
     public List<string> Get(int id)
     {
         List<string> result = new List<string>();
         using (var process = new Process())
         {
             process.StartInfo.FileName =  Path.Combine(_environment.WebRootPath,"files","HelloWorld.exe"); // relative path. absolute path works too. 
             process.StartInfo.Arguments = $"{id}"; 
             process.StartInfo.CreateNoWindow = true;
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.RedirectStandardError = true;


             process.OutputDataReceived += (sender, data) => result.Add(data.Data);
             process.ErrorDataReceived += (sender, data) => result.Add(data.Data);
             Console.WriteLine("starting");
             process.Start();
             process.BeginOutputReadLine();
             process.BeginErrorReadLine();     // (optional) wait up to 10 seconds
             do
             {
                 if (!process.HasExited)
                 {
                     // Refresh the current process property values.
                     process.Refresh(); 
                     Console.WriteLine($"exit {process.HasExited}");
                 }
             }
             while (!process.WaitForExit(1000));

         } 
         return result;
     }

Then, the result as below:

137576-image.png

[Note] In the above sample, I Copy the exe file to the wwwroot/files folder, if the console application code update, we should also update the exe file in the wwwroot/files folder.

Besides, in the console application, you can also export the output data to a temporary file under the wwwroot folder. Then, in the API action method you can get data from the temporary file.


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion




image.png (17.6 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.