Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 516
prosseek Avatar asked Oct 27 '25 09:10

prosseek


2 Answers

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();
like image 87
Guffa Avatar answered Oct 30 '25 13:10

Guffa


For simple cases, the advantage is mainly convenience. Obviously you have more options (working path, choosing between shell-exec, etc) with the ProcessStartInfo route, but there is also a Process.Start(ProcessStartInfo) static method.

Re checking for errors; Process.Start returns the Process object, so you can wait for exit and check the error code if you need. If you want to capture stderr, you probably want either of the ProcessStartInfo approaches.

like image 26
Marc Gravell Avatar answered Oct 30 '25 14:10

Marc Gravell