简体   繁体   中英

Process.Start() totally ignore the environment variables in PATH

I found that my cmd window prompted by Process.Start() totally ignore my environment variables in PATH. It always said that "xxx is not internal or external commands". I tried run it manually and it worked. Therefore, I am sure the PATH has been set correctly.

I also tried to add the variable explicitly. It still did not work. This is my code:

public static string ExecuteCommandSync(string command)
{
    try
    {
        System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("C:\\Windows\\System32\\cmd.exe", "/K " + command);

        var length = command.Length;

        procStartInfo.RedirectStandardOutput = false;
        procStartInfo.UseShellExecute = false;
        //Does not work
        procStartInfo.EnvironmentVariables.Add("PATH", "C:\\Program Files\\Arm\\Arm Mobile Studio 2021.0");
        procStartInfo.CreateNoWindow = false;
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
    }
    catch (Exception objException)
    {
        return objException.ToString();
    }
}

It is better when you did add the complete description of the error, in stead of "does not work"

System.ArgumentException: Value does not fall within the expected range. at System.Collections.Specialized.StringDictionaryWrapper.Add(String key, String value) at ConsoleApp88.Program.ExecuteCommandSync(String command) in

You cannot add PATH because it is already in the list of environment variables.

Solution can be to add the next statement, just before the add:

procStartInfo.EnvironmentVariables.Remove("PATH");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM