System.Environment.SetEnvironmentVariableCore C# (CSharp) Method

SetEnvironmentVariableCore() private static method

private static SetEnvironmentVariableCore ( string variable, string value, EnvironmentVariableTarget target ) : void
variable string
value string
target EnvironmentVariableTarget
return void
        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                SetEnvironmentVariableCore(variable, value);
            }
            else
            {
                RegistryKey baseKey;
                string keyName;

                if (target == EnvironmentVariableTarget.Machine)
                {
                    baseKey = Registry.LocalMachine;
                    keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
                }
                else
                {
                    Debug.Assert(target == EnvironmentVariableTarget.User);

                    // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
                    const int MaxUserEnvVariableLength = 255;
                    if (variable.Length >= MaxUserEnvVariableLength)
                    {
                        throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
                    }

                    baseKey = Registry.CurrentUser;
                    keyName = "Environment";
                }

                using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
                {
                    if (environmentKey != null)
                    {
                        if (value == null)
                        {
                            environmentKey.DeleteValue(variable, throwOnMissingValue: false);
                        }
                        else
                        {
                            environmentKey.SetValue(variable, value);
                        }
                    }
                }
            }

            //// Desktop sends a WM_SETTINGCHANGE message to all windows.  Not available on all platforms.
            //Interop.Kernel32.SendMessageTimeout(
            //    new IntPtr(Interop.Kernel32.HWND_BROADCAST), Interop.Kernel32.WM_SETTINGCHANGE,
            //    IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
        }

Same methods

Environment::SetEnvironmentVariableCore ( string variable, string value ) : void