简体   繁体   中英

pass custom environment variables to System.Diagnostics.Process

I'm working on an app that invokes external processes like so:

ProcessStartInfo startInfo = new ProcessStartInfo(PathToExecutable, Arguments){
     ErrorDialog = false,
     RedirectStandardError = true,
     RedirectStandardOutput = true,
     UseShellExecute = false,
     CreateNoWindow = true,
     WorkingDirectory = WorkingDirectory
 };

using (Process process = new Process()) {
    process.StartInfo = startInfo;

    process.Start();
    process.BeginErrorReadLine();
    process.BeginOutputReadLine();
    process.WaitForExit();

    return process.ExitCode;
}

One of the processes I'm calling depends on an environment variable that I'd rather not require my users to set. Is there any way to modify the environment variables that get sent to the external process? Ideally I'd be able to make them visible only to the process that's running, but if I have to programmatically set them system-wide, I'll settle for that (but, would UAC force me to run as administrator to do that?)

ProcessStartInfo.EnvironmentVariables is read only, so a lot of help that is...

You can add values to it though.

From MSDN ProcessStartInfo.EnvironmentVariables Property :

Although you cannot set the EnvironmentVariables property, you can modify the StringDictionary returned by the property. For example, the following code adds a TempPath environment variable: myProcess.StartInfo.EnvironmentVariables.Add("TempPath", "C:\\\\Temp") . You must set the UseShellExecute property to false to start the process after changing the EnvironmentVariables property. If UseShellExecute is true , an InvalidOperationException is thrown when the Start method is called.

您可以使用索引器设置环境变量:

process.StartInfo.EnvironmentVariables['name'] = value;

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