Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top