I’d love it if there was a nice clean way to do this; however, there isn’t. When running a process via the Process.Start(…) call one must provide a fully qualified path to an executable. The problem is that hard-coding the full path to the exe isn’t always the best option. This is why there is a “PATH” environment variable. The following expands the provided file name to the full qualified path by looking in the current directory and environment path variable:
/// <summary> /// Expands environment variables and, if unqualified, locates the exe in the working directory /// or the evironment's path. /// </summary> /// <param name="exe">The name of the executable file</param> /// <returns>The fully-qualified path to the file</returns> /// <exception cref="System.IO.FileNotFoundException">Raised when the exe was not found</exception> public static string FindExePath(string exe) { exe = Environment.ExpandEnvironmentVariables(exe); if (!File.Exists(exe)) { if (Path.GetDirectoryName(exe) == String.Empty) { foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';')) { string path = test.Trim(); if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe))) return Path.GetFullPath(path); } } throw new FileNotFoundException(new FileNotFoundException().Message, exe); } return Path.GetFullPath(exe); }
Most of this method is self-explanatory except the second if condition “Path.GetDirectoryName(exe) == String.Empty”. The reason for this is to determine if the name provided contains a ‘/’, ‘\’, ‘:’ or other path information. You might be able to replace it with an IndexOfAny(Path.GetInvalidFileNameChars()) or similar expression, but I thought this would produce more accurate results.