When do we need to set ProcessStartInfo.UseShellExecute to True?

The UseShellExecute boolean property is related to the use of the windows ShellExecute function vs the CreateProcess function – the short answer is that if UseShellExecute is true then the Process class will use the ShellExecute function, otherwise it will use CreateProcess.

The longer answer is that the ShellExecute function is used to open a specified program or file – it is roughly equivalnt to typing the command to be executed into the run dialog and clicking OK, which means that it can be used to (for example):

  • Open .html files or web using the default browser without needing to know what that browser is,
  • Open a word document without needing to know what the installation path for Word is
  • Run any command on the PATH

For example:

Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = "www.google.co.uk";
p.Start();

It is very easy to use, versatile and powerful however comes with some drawbacks:

  • It isn’t possible to redirect the standard input / output / error handles

  • It isn’t possibly to specify security descriptors (or other cool things) for the child process

  • There is a potential to introduce security vulnerabilities if you make assumptions about what will actually be run:

     // If there is an executable called "notepad.exe" somewhere on the path 
     // then this might not do what we expect
     p.StartInfo.FileName = "notepad.exe";
     p.Start();
    

CreateProcess is a far more precise way of starting a process – it doesn’t search the path and allows you to redirect the standard input or output of the child process (among other things). The disadvantage of CreateProcess however is that none of the 3 examples I gave above will work (try it and see).

In summary, you should set UseShellExecute to false if:

  • You want to redirect the standard input / output / error (this is the most common reason)
  • You don’t want to search the path for the executable (e.g. for security reasons)

Conversely you should keep UseShellExecute true if you want to open documents, urls or batch files etc… rather than having to explicitly give the path to an executable.

Leave a Comment