I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is:

        using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true))
            reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString);

Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.

+1  A: 

What OS is this? Is it on a 64-bit system? What is the nature of the failure: silent or is an exception thrown?

You could try running ProcessMonitor and seeing if it sees the attempt to set the value.

Rob Walker
+1  A: 

Is there any reason that you have to do it through the registry?

If not, you can use Environment.SetEnvironmentVariable() since .NET 2.0. It allows you to set on a machine, process or user basis.

Peter Hession

It turns out there was another problem that was preventing the code in my question from being called. However, I was using the Win32 assembly because the example code I was following was written before the Environment assembly became available. So Thanks Peter for pointing out the Environment API.

Brian Stewart
+1  A: 

Why are you using a CustomAction for this? The Windows Installer supports updating environment variables natively.

Rob Mensching