Hi @Andrew Harkins ,
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:
[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