Search code examples
c#processinterprocess

Process.Start vs Process `p = new Process()` in C#?


As is asked in this post, there are two ways to call another process in C#.

Process.Start("hello");

And

Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
  • Q1 : What are the pros/cons of each approach?
  • Q2 : How to check if error happens with the Process.Start() method?

Solution

  • With the first method you might not be able to use WaitForExit, as the method returns null if the process is already running.

    How you check if a new process was started differs between the methods. The first one returns a Process object or null:

    Process p = Process.Start("hello");
    if (p != null) {
      // A new process was started
      // Here it's possible to wait for it to end:
      p.WaitForExit();
    } else {
      // The process was already running
    }
    

    The second one returns a bool:

    Process p = new Process();
    p.StartInfo.FileName = "hello.exe";
    bool s = p.Start();
    if (s) {
      // A new process was started
    } else {
      // The process was already running
    }
    p.WaitForExit();