I have a VB6 executable which is accessing some system environment variables. I have implemented a .NET console application which checks if those environment variables exist, creates them if needed, and then runs the VB6 application by calling Process.Start
.
Doing this, the VB6 application cannot find the environment variables and it says they don't exist.
If I run the VB6 application from Windows Explorer it works fine and can find the variables.
So it seems the VB6 app is running under the context of .NET console app and cannot access the system environment variables!
Code to set the environment vars .NET Cosnole app:
foreach(var varObject in Variables)
{
var envVar = Envrionment.GetEnvironmentVariable(varObject.Name ,
EnvironmentVariableTarget.Machine);
if(string.IsNullOrEmpty(envVar)
{
Environment.SetEnvironmentVariable(varObject.Name,varObject.Value,
EnvironmentVariableTarget.Machine);
}
}
Code to run the VB6 app from .NET Cosnole app:
var processInfo = new ProcessStartInfo(VB6ApplicationFilePath);
processInfo.UseShellExecute = true
processInfo.WindwoStyle= ProcessWindowStyle.Hidden;
Process.Start(processInfo);
A copy of a program's environment is passed to a program that it starts. As it is a copy the second program only sees the state it was in when given it (and changes it made). No other program can change another program's environment.
When using
ShellExecute
(which you tellProcessStart
to) you are asking Explorer to start the program for you. The program will get a copy of Explorer's environment.When changing the system environment, programs can send a message to all windows open saying environment has changed (as
setx
does - seesetx /?
). But ONLY Explorer.exe pays attention to this message. So only programs started by explorer after explorer receives this message will see the changes.These are the API calls that .NET calls. In Windows all programs are started by
CreateProcessEx
(or older programsCreateProcess
).Shellexecute
andShellexecuteEx
process the command like you typed it in Explorer's Start - Run dialog (Winkey + R) then changes it and callsCreateProcessEx
.At the command prompt. Type
We set an environment variable, start a new command prompt that prints that variable.
This is the message that notifies