2017-08-25 116 views
1

我有一個批處理文件setEnv.bat從C#應用程序批量設置訪問變量

@echo off 
set input=C:\Program Files\Java\jdk1.8.0_131 
SET MY_VAR=%input% 

我想運行從C#應用此批處理文件,要訪問的MY_VAR從C#應用新設置的值。

C#:

System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
proc.StartInfo.FileName= "D:\\Check\\SetJavaHome.bat"; 
proc.StartInfo.WorkingDirectory = 
System.Environment.CurrentDirectory; 
proc.Start(); 

串myVar的= Environment.GetEnvironmentVariable( 「MY_VAR」);

有人可以幫助我按預期工作嗎?

在此先感謝。

+2

只有在使用'SETX'在註冊表中寫入變量或者從批處理文件中調用該程序時,纔可以訪問該變量。 – npocmaka

+0

我正在從C#程序調用批處理文件。 – Ashley

+0

您可以將文件讀取爲文本,並使用正則表達式來解析文件並獲取值:p – Derek

回答

0

你想這樣做的原因有點含糊,但如果你唯一的選擇是從Process.Start的調用中運行該批處理文件,那麼下面的技巧可以讓你將環境變量從批處理文件提升到你自己的進程。

這是批處理文件我使用:

set test1=fu 
set test2=bar 

的followng代碼打開一個標準的命令提示符,然後使用StandardInput將命令發送到命令提示符並與OutputDataReceived event收到了效果。我基本上將SET命令的輸出和對其結果的解析結合起來。對於包含環境變量和值的每一行,我都會調用Environment.SetEnvironmentVaruable來在我們自己的過程中設置環境。

var sb = new StringBuilder(); 
bool capture = false; 

var proc = new Process(); 
// we run cms on our own 
proc.StartInfo.FileName = "cmd"; 
// we want to capture and control output and input 
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardOutput = true; 
proc.StartInfo.RedirectStandardInput = true; 

// get all output from the commandline 
proc.OutputDataReceived += (s, e) => { if (capture) sb.AppendLine(e.Data); }; 

// start 
proc.Start(); 
proc.BeginOutputReadLine(); // will start raising the OutputDataReceived 

proc.StandardInput.WriteLine(@"cd \tmp"); // where is the cmd file 
System.Threading.Thread.Sleep(1000); // give it a second 
proc.StandardInput.WriteLine(@"setenv.cmd"); // run the cmd file 
System.Threading.Thread.Sleep(1000); // give it a second 

capture = true; // what comes next is of our interest 
proc.StandardInput.WriteLine(@"set"); // this will list all environmentvars for that process 
System.Threading.Thread.Sleep(1000); // give it a second 
proc.StandardInput.WriteLine(@"exit"); // done 
proc.WaitForExit(); 

// parse our result, line by line 
var sr = new StringReader(sb.ToString()); 
string line = sr.ReadLine(); 
while (line != null) 
{ 
    var firstEquals = line.IndexOf('='); 
    if (firstEquals > -1) 
    { 
     // until the first = will be the name 
     var envname = line.Substring(0, firstEquals); 
     // rest is the value 
     var envvalue = line.Substring(firstEquals+1); 
     // capture what is of interest 
     if (envname.StartsWith("test")) 
     { 
      Environment.SetEnvironmentVariable(envname, envvalue); 
     } 
    } 
    line = sr.ReadLine(); 
} 
Console.WriteLine(Environment.GetEnvironmentVariable("test2")); // will print > bar 

這會將由命令文件設置的環境變量帶入您的進程。

請注意,您可以通過創建首先調用您的批處理文件,然後啓動你的程序的命令文件實現相同的:

rem set all environment vars 
setenv.cmd 
rem call our actual program 
rem the environment vars are inherited from this process 
ConsoleApplication.exe 

後者更容易,開箱的,不易碎的解析代碼所需。