应用程序如何访问另一个应用程序设置的环境变量? [英] How can an application access the environment variable set by another application?
问题描述
在这种情况下,设置环境变量的应用程序在需要访问env.var的应用程序中执行。
Main()返回值(C#编程指南) msdn文章讨论了它在批处理文件中的使用。如果我也一样,一切都很好但是需要的是不要从批处理脚本运行,而是从应用程序中运行。
In this case the application which sets the environment variable is executed in/from the application that needs to access the env.var. The Main() Return Values (C# Programming Guide) msdn article discusses its use within a batch file. If I try the same, everything is fine; but what is required is to run not from a batch script but from within an application.
Process.Start("app","args"); // app sets the env.var.
string envVar = System.Environment.GetEnvironmentVariable("ERRORLEVEL");
显然不成功。 Process.Start使app在一个完全不同的环境中工作,我相信。换句话说,我需要在与调用者应用程序相同的环境中运行app,以达到它设置的环境变量。
was obviously unsuccessful. Process.Start made the "app" work in a completely different environment I believe. In other words, I need to run "app" in the same environment as the caller application in order to reach the environment variable it sets.
推荐答案
如果您只想从父级设置孩子的环境:
If you're just trying to set the child's environment from the parent:
var p = new Process();
p.StartInfo.EnvironmentVariables["TEST_ENV"] = "From parent";
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:\src\bin\Debug\ChildProc.exe";
p.Start();
如果您不希望子代继承父进程环境:
If you don't want the child to inherit the parent process environment:
var psi = new ProcessStartInfo();
psi.EnvironmentVariables["TEST_ENV"] = "From parent";
psi.UseShellExecute = false;
psi.FileName = @"C:\src\bin\Debug\ChildProc.exe";
Process.Start(psi);
这篇关于应用程序如何访问另一个应用程序设置的环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!