简体   繁体   English

Process.Start() 完全忽略 PATH 中的环境变量

[英]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.我发现我的 cmd window 由 Process.Start() 提示完全忽略了我在 PATH 中的环境变量。 It always said that "xxx is not internal or external commands".它总是说“xxx不是内部或外部命令”。 I tried run it manually and it worked.我尝试手动运行它并且它工作。 Therefore, I am sure the PATH has been set correctly.因此,我确信 PATH 已正确设置。

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. System.ArgumentException:值不在预期范围内。 at System.Collections.Specialized.StringDictionaryWrapper.Add(String key, String value) at ConsoleApp88.Program.ExecuteCommandSync(String command) in在 System.Collections.Specialized.StringDictionaryWrapper.Add(String key, String value) 在 ConsoleApp88.Program.ExecuteCommandSync(String command) 中

You cannot add PATH because it is already in the list of environment variables.您不能添加PATH ,因为它已经在环境变量列表中。

Solution can be to add the next statement, just before the add:解决方案可以是在添加之前添加下一条语句:

procStartInfo.EnvironmentVariables.Remove("PATH");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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