Making .NET SetEnvironmentVariable call "stick" across .NET / COM

Posted on 2003-11-18
Last Modified: 2013-11-25
OK, I think the title sums up what I need. I am writing a C# application (.exe) which includes an old DLL written by another segment of my company. It is in VB and simplifies calls to a third party application. This application needs an environment variable set in order to run. I did this once
a couple of years ago in C++ / COM and had no problem. I set the env variable when my code started
and all subsequent calls to the third party application worked well with the env variable set.
Now on to C#. I have used the DllImportAttribute to bring in kernel32.dll and declared my SetEnvironmentVariable() method. All appears to be ok (no compile errors, sets the env variable as checked later by GetEnvironmentVariable()). But when I make my calls to the VB dll, the third party application fails (properly, cleanly, etc) because it doesn't see this environment variable. If I just set the environment variable through the Windows control panel, the code runs fine. I figure this has to do with the Application Domains / Process  model of .NET, but I can't figure out how to work around it.

Here is the DllImport, just so you can see some code, but I don't know what else could really help...

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]      
public static extern bool SetEnvironmentVariable(string lpname, string lpvalue);

I have made direct calls to the above, and I have followed the MSDN method and called the following method:

public static bool SetEnvironmentVariableEx(string evar, string eval) {
   try {
      // Get the write permission to set the environment variable.
      EnvironmentPermission ep = new EnvironmentPermission(EnvironmentPermissionAccess.Write,evar);
      return SetEnvironmentVariable(evar, eval);
   catch( Exception e) {
      Console.WriteLine("Exception:" + e.Message);
      return false;

And finally, the project requires the inclusion of COMSVCSLIB.dll and does not produce a library named InterOp.XXXX.dll as many of old COM dll's do. I am still uncertain about the details of Interop, so I am not sure why this is.

Thanks for any help

Question by:jmuldrum
  • 3
  • 2
LVL 48

Expert Comment

ID: 9771119
Write required environment variable directlly to Registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
using Registry .NET class.
LVL 48

Expert Comment

ID: 9771177
It should be something like this:

RegistryKey regkey;
String keyValue;

keyValue = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
regkey = Registry.LocalMachine.OpenSubKey(keyValue, True);
regkey.SetValue("Variable name", "Variable value");


Author Comment

ID: 9771178
Thanks for the quick response.... I will work on that in a few minutes, but how would this affect other applications running on the same machine which would use the same env. variable but with a different value?

LVL 48

Accepted Solution

AlexFM earned 500 total points
ID: 9771285
Agree, this is not clean. Use this only if there is no othe ways.
I can think about following ways:
1) Use HKEY_CURRENT_USER instead of HKEY_LOCAL_MACHINE (user instead of system environment variable)
2) Delete it when you don't need it more
3) You can write small application which runs your own application using CreateProcess API. It allows to redefine environment variables for created process.

Author Comment

ID: 9771336
I had thought about usig CreateProcess(), but this little "experiment" will eventually make its way into an application which requires a lot of data be passed. I am connecting to a wrapper for MQSeries, so  moving this data across a process boundary is something I would rather not try to do unless no other way exist. Thanks for the info. I will try to test it this morning.
In the meantime, if anything else occurs to you, let me know


Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK ( for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA.…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question