从C#应用程序批量设置访问变量

我有一个批处理文件setEnv.bat

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

我想从C#应用程序运行这个批处理文件,并希望从c#application访问新设置的MY_VAR值。

C#:

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

string myVar = Environment.GetEnvironmentVariable(“MY_VAR”);

有人可以帮助我按预期工作吗?

提前致谢。

请使用示例代码查看此答案: https : //stackoverflow.com/a/51189308/9630273

直接从另一个进程获取环境变量是不可能的,但一个简单的解决方法可能是:

创建一个虚拟bat文件(env.bat),它将执行所需的bat并回显环境变量。 在C#的进程执行中获取此env.bat的输出。

您想要这样做的原因有点模糊,但如果您唯一的选择是从调用Process.Start运行该批处理文件,那么以下技巧将允许您将环境变量从批处理文件提升到您自己的进程。

这是我使用的批处理文件:

 set test1=fu set test2=bar 

以下代码打开标准命令提示符,然后使用StandardInput将命令发送到命令提示符,并使用OutputDataReceived事件接收结果。 我基本上捕获SET命令的输出和解析结果。 对于包含环境var和值的每一行,我调用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 

后者更容易,开箱即用,不需要脆弱的解析代码。