簡體   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