Search code examples
c#environment-variablessystem.diagnostics

System.Diagnostics.Process(); StartInfo.Arguments use Environment Variables as argument


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();

Solution

  • 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.