繁体   English   中英

设置流程的环境变量

[英]Set environment variables for a process

什么是环境变量概念?

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

  1. 我创建了一个进程,并在StartInfo中设置了两个变量。 变量已经存在,但缺少所需的信息。
  2. 我试图用System.Environment.SetEnvironmentVariable()设置变量。

当我运行该进程时,系统找不到可执行文件(“ executeable1”)。 我试图将StartInfo.FileName设置为“ executeable1”的完整路径-但是,然后找不到在“ executeable1”内称为form的EXE文件...

我该如何处理?

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词典属性:

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);

环境变量有很多类型,例如系统级别和用户。 这取决于您的要求。

要设置环境变量,只需使用Get Set方法。 将变量名称和值作为参数传递,并且如果用于定义访问级别,则必须随其传递。 要访问该值,则也可以使用Set方法来传递访问级别参数。

例如,我正在定义用户级变量:

//For setting and defining variables
System.Environment.SetEnvironmentVariable("PathDB", txtPathSave.Text, EnvironmentVariableTarget.User);
System.Environment.SetEnvironmentVariable("DBname", comboBoxDataBaseName.Text, EnvironmentVariableTarget.User);

//For getting
string Pathsave = System.Environment.GetEnvironmentVariable("PathDB", EnvironmentVariableTarget.User);
string DBselect = System.Environment.GetEnvironmentVariable("DBname", EnvironmentVariableTarget.User);

暂无
暂无

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

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