为进程设置环境变量 [英] Set environment variables for a process

查看:179
本文介绍了为进程设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是环境变量概念?

在C#程序中,我需要调用一个可执行文件。可执行文件将调用驻留在同一文件夹中的其他一些可执行文件。可执行文件依赖于两个环境变量PATH和RAYPATH的设置。我尝试了以下两件事:

In a C# program I need to call an executable. The executable will call some other executables that reside in the same folder. The executables rely on the two environment variables "PATH" and "RAYPATH" to be set correctly. I tried the following two things:


  1. 我创建了一个进程,并在StartInfo中设置两个变量。
    变量已经存在,但是缺少所需的信息。

  2. 我尝试使用
    设置变量System.Environment.SetEnvironmentVariable()。

当我运行该进程时,系统找不到可执行文件(executeable1)。我试图将StartInfo.FileName设置为executeable1的完整路径 - 然而,在executeable1中调用的EXE文件没有被找到...

When I run the process the system can't find the executable ("executeable1"). I tried to set StartInfo.FileName to the full path of "executeable1" - however then the EXE files called form within "executeable1" are not found...

我处理这个?

string pathvar = System.Environment.GetEnvironmentVariable("PATH");
System.Environment.SetEnvironmentVariable("PATH", pathvar + @";C:\UD_\bin\DAYSIM\bin_windows\;C:\UD_\bin\Radiance\bin\;C:\UD_\bin\DAYSIM;");
System.Environment.SetEnvironmentVariable("RAYPATH", @"C:\UD_\bin\DAYSIM\lib\;C:\UD_\bin\Radiance\lib\");

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.WorkingDirectory = @"C:\UD_\bin\DAYSIM\bin_windows";

//string pathvar = p.StartInfo.EnvironmentVariables["PATH"];
//p.StartInfo.EnvironmentVariables["PATH"] = pathvar + @";C:\UD_\bin\DAYSIM\bin_windows\;C:\UD_\bin\Radiance\bin\;C:\UD_\bin\DAYSIM;";
//p.StartInfo.EnvironmentVariables["RAYPATH"] = @"C:\UD_\bin\DAYSIM\lib\;C:\UD_\bin\Radiance\lib\";


p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;

p.StartInfo.FileName = "executeable1";
p.StartInfo.Arguments = arg1 + " " + arg2;
p.Start();
p.WaitForExit();


推荐答案

System.Environment.SetEnvironmentVariable 更改当前进程 的环境变量。如果要更改创建的进程的变量,只需使用 EnvironmentVariables 字典属性:

What is your problem actually? System.Environment.SetEnvironmentVariable changes the environment variables of the current process. If you want to change the variables of a process you create, just use the EnvironmentVariables dictionary property:

var startInfo = new ProcessStartInfo();

// Sets RAYPATH variable to "test"
// The new process will have RAYPATH variable created with "test" value
// All environment variables of the created process are inherited from the
// current process
startInfo.EnvironmentVariables["RAYPATH"] = "test";

// Required for EnvironmentVariables to be set
startInfo.UseShellExecute = false;

// Sets some executable name
// The executable will be search in directories that are specified
// in the PATH variable of the current process
startInfo.FileName = "cmd.exe";

// Starts process
Process.Start(startInfo);

这篇关于为进程设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆