예제 #1
0
        private static void SetEnvironmentVariable(string name, string value, SetVariableFlags flag,
                                                   EnvironmentVariableTarget target)
        {
            var current = Environment.GetEnvironmentVariable(name, target);

            if (current != null)
            {
                if (flag.HasFlag(SetVariableFlags.Append))
                {
                    if (current.Split(';').Contains(value, true))
                    {
                        throw new ValueExistsException();
                    }
                    Environment.SetEnvironmentVariable(name, string.Join(";", current, value), target);
                }
                else if (flag.HasFlag(SetVariableFlags.Overwrite))
                {
                    Environment.SetEnvironmentVariable(name, value, target);
                }
                else
                {
                    throw new InvalidOperationException("The specified variable already exists.");
                }
            }
            else
            {
                Environment.SetEnvironmentVariable(name, value, target);
            }

            const int timeoutMilliseconds = 15000;

            var result = SendMessageTimeout(
                HWND_BROADCAST,
                WM_SETTINGCHANGE,
                UIntPtr.Zero,
                Marshal.StringToHGlobalUni("Environment"),
                SMTO_ABORTIFHUNG,
                timeoutMilliseconds,
                out _);

            if (result != IntPtr.Zero)
            {
                return;
            }

            var win32Err = Marshal.GetLastWin32Error();

            if ((ulong)win32Err == ERROR_TIMEOUT)
            {
                throw new TimeoutException("The SendMessage operation timed out.");
            }

            throw new Win32Exception(win32Err);
        }
예제 #2
0
 public static void SetSystemVariable(string name, string value, SetVariableFlags flag)
 {
     SetEnvironmentVariable(name, value, flag, EnvironmentVariableTarget.Machine);
 }
예제 #3
0
 public static void SetUserVariable(string name, string value, SetVariableFlags flag)
 {
     SetEnvironmentVariable(name, value, flag, EnvironmentVariableTarget.User);
 }