How do I ensure C#'s Process.Start will expand environment variables?
Asked Answered
T

2

12

I'm attempting to create a process like so:

var psi = new ProcessStartInfo
{
    FileName = @"%red_root%\bin\texturepreviewer.exe",
    UseShellExecute = true
};

var process = Process.Start(psi);
process.WaitForExit();

Now the environment variable "red_root" definitely exists in the spawned process' environment variables, but the execute doesn't seem to expand the environment variable and so the file isn't found. How can I get the Process.Start to expand the environment variable in the file name?

Tedder answered 8/12, 2010 at 14:35 Comment(0)
A
25

The Environment.ExpandEnvironmentVariables method should help here.

Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.

string unexpandedPath = "%red_root%\\bin\\texturepreviewer.exe";   
psi.FileName = Environment.ExpandEnvironmentVariables(unexpandedPath);
Aeronaut answered 8/12, 2010 at 14:39 Comment(1)
Looks like this method has been around since .NET 1.1 so it's pretty safe to use nowadays.Heribertoheringer
C
6

Have you tried System.Environment.GetEnvironmentVariable ("red_root", EnvironmentVariableTarget.Machine) ?

Coriolanus answered 8/12, 2010 at 14:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.