Calling another process from C# console app

Goal of this post is to show how to call an exe from another program.

Tool/prerequisites we are going to use: Visual Studio, .NET 6.

GitRepo is available here.

Calling another process and capturing it’s output is really straightforward in .NET. We just need to create a new ProcessStartInfo with the needed parameters and pass it to the Process.Start method. That is all.

Here we have a solution with two projects. The first project is receiving two parameters and writes out a number in a loop, then the second project is depending on the first one, calls it and captures it’s output.

“Counter” project’s code:

public class Program
{
    public static void Main(string[] args)
    {
        int start = Convert.ToInt32(args[0]);
        int end = Convert.ToInt32(args[1]);

        for (int current = start; current < end; current++)
        {
            Console.WriteLine(current);
        }
    }
}

Note: there is no safeguarding on the parameters, as it is just an example project.

“Caller” project’s code:

using System.Diagnostics;


var proc = Process.Start(new ProcessStartInfo
{
    // Arguments to pass to another process, separated by a space
    Arguments = "10 20",
    // Name of the exe file. Note: it will be copied by the builder (Visual Studio) to the projects bin folder, as it is dependent on the project "BlodDavid_CounterProject"
    FileName = "BlodDavid_CounterProject.exe",
    // To redirect the output stream, we need to set it to false
    UseShellExecute = false,
    // We want to capture the data written to the output of the other process
    RedirectStandardOutput = true,
    // We don't want to show the users another windows, just the output in our main app
    CreateNoWindow = true
});

// Starting the another process
proc.Start();

// Listening to the output stream
while (!proc.StandardOutput.EndOfStream)
{
    Console.WriteLine($"Message from the other process: {proc.StandardOutput.ReadLine()}");
}
// Don't let our program to exit until the other process finishes
proc.WaitForExit();

// Notifying our user that the other project ended
Console.WriteLine("To exit press enter!");
Console.ReadLine();

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.