Process.Start filename using %temp%

为君一笑 提交于 2019-12-01 23:28:36

The Process class does not expand strings with environment variables (i.e. %temp%).

If you want to use environment variables to build the FileName property then you'll have to get the environment variables (using the GetEnvironmentVariable method on the Environment class) and perform the substitution yourself, like so:

// Construct the path.
string temp = Environment.GetEnvironmentVariable("temp");
string path = Path.Combine(temp, "SSCERuntime_x86-ENU.msi");

// Launch the process.
Process p = new Process();
p.StartInfo.FileName = path;
p.StartInfo.Arguments = "/passive";
p.Start();

Additionally, you can use the ExpandEnvironmentVariables method with your original string like so:

p.StartInfo.FileName = 
    Environment.ExpandEnvironmentVariables(@"%temp%\SSCERuntime_x86-ENU.msi");

The %temp% portion of the string is being interpreted literally instead of being replaced with the appropriate environment variable. You'll need to manually expand it

var temp = Environment.GetEnvironmentVariable("temp");
var fileName = Path.Combine(temp, "SSCERuntime_x86-ENU.msi");
p.StartInfo.FileName = fileName;

%TEMP% is parsed and evaluated by Command Shell. You could use use Path.GetTempPath() and Path.Combine for this purpose.

p.StartInfo.FileName = Path.Combine(Path.GetTempPath(), @"SSCERuntime_x86-ENU.msi");

You can use the Environment.ExpandEnvironmentVariables to expand environment variables within a string, then pass that to the Process class:

p.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%temp%\SSCERuntime_x86-ENU.msi");

This has the added benefits of

  1. Working for any environment variable (%APPDATA%, %COMMONPROGRAMFILES%, etc), and
  2. Working anywhere in the string (e.g. "%temp%\%username%\foo.txt")

Try this:

string tempPath = Environment.GetEnvironmentVariable("Temp");

Then concat it in:

p.StartInfo.FileName = Path.Combine(tempPath, "SSCERuntime_x86-ENU.msi"); 

Casper beat me to the punch on the explaination, but the Process.Start method basically treats it literally instead of intrperting it as the shell would.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!