Saturday, April 08, 2006
« Web Application Projects RC1 Released | Main | Officially 2 Years Old »

The other day I started to write a new utility application which, among its various tasks, launches applications as specified by the user.  Typically, the user may enter or browse to a folder such as "C:\Program Files\Some Application\DummyApp.exe".  Passing this path to the Process class's Start() method will then launch the application as in the following contrived examples (which are conspicuously devoid of any error handling code - don't try this at home):

using System.Diagnostics;

// in some class somewhere...
private void launchSomeApp() {
   string appPath = "\"C:\\Program Files\\Some Application\\DummyApp.exe\"";
   Process.Start(appPath);
}

However, suppose the user providing the application path in the following format:

string appPath = "\"%ProgramFiles%\\Some Application\\DummyApp.exe\"";

That path is perfectly valid and typing it at the command prompt will execute the application properly (provided it actually exists).  However, it appears that using environment variables within your path provided to the Process.Start() method it will fail to execute.  Using either the previously mentioned code or the following will yield a "The system cannot find the file specified." error message.

private void launchSomeApp() {
   string appPath = "\"%ProgramFiles%\\Some Application\\DummyApp.exe\"";
   ProcessStartInfo startInfo = new ProcessStartInfo();
   startInfo.FileName = appPath;
   Process.Start(startInfo);
}

You might be tempted to go down the path, to experiment with the EnvironmentVariables property of ProcessStartInfo along with UseShellExecute and others.  This will all be in vain.  Effectively, the EnvironmentVariables property creates a copy of the executing application's environment variables when first referenced.  This provides a means by which the program can edit, clear, add, or even remove environment variables for the invoked process.  Note that these variables are available TO the process as environment variable, not the process invoking the new process as such.  Therefore, they have no effect on the command string.

Well, fortunately, it's not too difficult to overcome.  Built-in to the Environment class is a method which takes a string and substitutes environment variables for you.  Now users of this utility application can specify paths however they see fit (using environment variables or not), and the application will continue to work as expected.  Simple.  And saves me from having to write my own 'Environment Variable Expander' method.

private void launchSomeApp() {
   string appPath = "\"%ProgramFiles%\\Some Application\\DummyApp.exe\"";
   ProcessStartInfo startInfo = new ProcessStartInfo();
   startInfo.FileName = Environment.ExpandEnvironmentVariables(appPath);
   Process.Start(startInfo);
}

Saturday, April 08, 2006 6:01:00 PM (Mountain Standard Time, UTC-07:00)  #    Disclaimer  |  Comments [0]  |  Trackback