设置进程的环境变量

时间:2013-01-28 00:16:13

标签: c# windows environment-variables processstartinfo

什么是环境变量概念?

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

  1. 我创建了一个进程并在StartInfo中设置了两个可变数据。该 变量已存在但缺少所需信息。
  2. 我尝试用变量设置变量     System.Environment.SetEnvironmentVariable()。
  3. 当我运行该进程时,系统找不到可执行文件(“executeable1”)。我试图将StartInfo.FileName设置为“executeable1”的完整路径 - 然后找不到在“executeable1”中调用表单的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();
    

2 个答案:

答案 0 :(得分:72)

实际上你的问题是什么? 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);

答案 1 :(得分:5)

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

要设置环境变量,只需使用Get Set方法。将变量Name和Value作为参数传递,如果用于定义访问级别,则必须传递它。要访问该值,请使用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);
相关问题