Brian Stewart
Brian Stewart

Reputation: 9287

Cannot create an environment variable in the registry

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.

Upvotes: 0

Views: 1199

Answers (4)

Rob Mensching
Rob Mensching

Reputation: 35976

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

Upvotes: 1

Brian Stewart
Brian Stewart

Reputation: 9287

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.

Upvotes: 0

Peter Hession
Peter Hession

Reputation: 499

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.

Upvotes: 1

Rob Walker
Rob Walker

Reputation: 47482

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.

Upvotes: 1

Related Questions