2

How is it possible to pass environment variables as arguments to a System.Diagnostics.Process()? Using a variable path fails for some reason. For instance, I'm trying to open explorer at the path %windir%, this fails:

program: explorer.exe args: /n, /e, %windir%

var f = new System.Diagnostics.Process();
f.StartInfo.WorkingDirectory = Path.GetDirectoryName(Program);
f.StartInfo.FileName = Program;
f.StartInfo.Arguments = !string.IsNullOrWhiteSpace(Params) ? Params : null;
f.Start();
Klors
  • 2,665
  • 2
  • 25
  • 42
user937036
  • 341
  • 1
  • 3
  • 15
  • Interpreting %windir% is a job of the command processor, Cmd.exe. You'll have to do it yourself now, use Environment.GetFolderPath(). Or use Cmd.exe, /c command line option. – Hans Passant Oct 22 '15 at 16:48
  • Possible duplicate of [How do I get and set Environment variables in C#?](http://stackoverflow.com/questions/185208/how-do-i-get-and-set-environment-variables-in-c) – Thomas Weller Oct 22 '15 at 17:29

1 Answers1

3

As commenter Hans Passant says, syntax like %windir% is specific to the command line processor. You can emulate it in your own code by calling Environment.GetEnvironmentVariable("windir") (i.e. to get the current value of the WINDIR environment variable), or Environment.GetFolderPath(SpecialFolder.Windows) (i.e. to have Windows report the path of the known special folder).

If you want to have the command line processor do the work, you need to run the command line processor. E.g.:

f.StartInfo.FileName = "cmd.exe";
f.StartInfo.Arguments = "/c explorer.exe /n /e /select,%windir%";

That will run cmd.exe, which in turn will start the explorer.exe process on your behalf, parsing the %windir% expression as an environment variable dereference.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136