Beispiel #1
0
        /// <summary>
        /// Retrieves all environment variable names and their values
        /// from the Windows operating system registry key for the
        /// current user or local machine.
        /// </summary>
        /// <param name="target">
        /// One of the <see cref="System.EnvironmentVariableTarget" /> values.
        /// </param>
        /// <returns>
        /// A dictionary that contains all environment variables
        /// names and their values from the source specified by the
        /// target parameter; otherwise, an empty dictionary if no
        /// environment variables are found.
        /// </returns>
        public static IDictionary<string, string> GetEnvironmentVariables(EnvironmentVariableTarget target)
        {
            Dictionary<string, string> variables = new Dictionary<string, string>();

            string keyName;
            RegistryKey registryKey;

            switch (target)
            {
                case EnvironmentVariableTarget.Machine:
                    keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
                    registryKey = Registry.LocalMachine.OpenSubKey(keyName);
                    break;
                case EnvironmentVariableTarget.User:
                    keyName = @"Environment";
                    registryKey = Registry.CurrentUser.OpenSubKey(keyName);
                    break;
                default:
                    throw new ArgumentException("Invalid environment variable target", "target");
            }

            foreach (string name in registryKey.GetValueNames())
            {
                variables.Add(name, (string)registryKey.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames));
            }

            return variables;
        }
Beispiel #2
0
        private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                return GetEnvironmentVariableCore(variable);
            }
            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);
                    baseKey = Registry.CurrentUser;
                    keyName = "Environment";
                }

                using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
                {
                    return environmentKey?.GetValue(variable) as string;
                }
            }
        }
        private string GetExisting(EnvironmentVariableTarget target, string variableName)
        {
            var existingVariable = _variables[target][variableName];
            if (!IsValid(existingVariable)) UpdateVariable(existingVariable);

            return existingVariable.Content;
        }
Beispiel #4
0
        /// <summary>
        /// Creates, modifies, or deletes an environment variable stored
        /// in the Windows operating system registry key reserved for the
        /// current user or local machine.
        /// </summary>
        /// <param name="variable">
        /// The name of an environment variable.
        /// </param>
        /// <param name="value">A value to assign to variable.</param>
        /// <param name="target">
        /// One of the <see cref="System.EnvironmentVariableTarget" /> values.
        /// </param>
        public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
        {
            string keyName;
            RegistryKey registryKey;

            switch (target)
            {
                case EnvironmentVariableTarget.Machine:
                    keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
                    registryKey = Registry.LocalMachine.OpenSubKey(keyName, true);
                    break;
                case EnvironmentVariableTarget.User:
                    keyName = @"Environment";
                    registryKey = Registry.CurrentUser.OpenSubKey(keyName, true);
                    break;
                default:
                    throw new ArgumentException("Invalid environment variable target", "target");
            }

            if (value == null)
            {
                registryKey.DeleteValue(variable, false);
            }
            else
            {
                registryKey.SetValue(variable, value, RegistryValueKind.ExpandString);
            }

            Notification.EnvironmentChanged();
        }
Beispiel #5
0
 public static void AllVariables(EnvironmentVariableTarget target)
 {
     foreach (DictionaryEntry var in Environment.GetEnvironmentVariables(target))
     {
         string key = (string)var.Key;
         string value = (string)var.Value;
         ConsoleHelper.WriteLine(key + ": " + value);
     }
 }
 public string Get(string variableName, EnvironmentVariableTarget target)
 {
     lock (LockKey)
     {
         return _variables[target].ContainsKey(variableName)
                    ? GetExisting(target, variableName)
                    : GetNew(target, variableName);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Loads the environment variables.
        /// </summary>
        /// <param name="dg">The Data Grid View.</param>
        /// <param name="target">The target.</param>
        private void LoadEnvironmentVariables(
            DataGrid dg, EnvironmentVariableTarget target)
        {
            dg.IsReadOnly = true;

            IDictionary environmentVariables
                = this.variableManger.GetEnvVariables(target);

            dg.ItemsSource = environmentVariables;
        }
Beispiel #8
0
        public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
        {
            if (variable == null)
            {
                throw new ArgumentNullException(nameof(variable));
            }

            ValidateTarget(target);

            return GetEnvironmentVariableCore(variable, target);
        }
        public bool Exists(string variableName, EnvironmentVariableTarget target)
        {
            lock (LockKey)
            {
                if (_variables[target].ContainsKey(variableName) && _variables[target][variableName].Content != null) return true;

                var variable = System.Environment.GetEnvironmentVariable(variableName, target);

                return variable != null;
            }
        }
Beispiel #10
0
        /// <summary>
        /// This program allows you to view and modify the PATH environment.
        /// </summary>
        /// <param name="args"></param>
        private void Run(string[] args)
        {
            Console.OutputEncoding = Encoding.GetEncoding(Encoding.Default.CodePage);
            Args = new InputArgs("pathed", string.Format(resource.IDS_TITLE, AppVersion.Get()) + "\r\n" + resource.IDS_COPYRIGHT);

            Args.Add(InputArgType.Flag, "machine", false, Presence.Optional, resource.IDS_CMD_machine_doc);
            Args.Add(InputArgType.Flag, "user", false, Presence.Optional, resource.IDS_CMD_user_doc);
            Args.Add(InputArgType.ExistingDirectory, "add", "", Presence.Optional, resource.IDS_CMD_add_doc);
            Args.Add(InputArgType.ExistingDirectory, "append", "", Presence.Optional, resource.IDS_CMD_append_doc);
            Args.Add(InputArgType.StringList, "remove", null, Presence.Optional, resource.IDS_CMD_remove_doc);
            Args.Add(InputArgType.Flag, "slim", false, Presence.Optional, resource.IDS_CMD_slim_doc);
            Args.Add(InputArgType.Parameter, "env", "PATH", Presence.Optional, resource.IDS_CMD_env_doc);

            if (Args.Process(args))
            {
                EnvironmentVariableName = Args.GetString("env");

                if (Args.GetFlag("slim"))
                    SlimPath();

                if (Args.GetFlag("machine"))
                    EnvironmentVariableTarget = EnvironmentVariableTarget.Machine;

                else if (Args.GetFlag("user"))
                    EnvironmentVariableTarget = EnvironmentVariableTarget.User;

                try
                {
                    List<string> removeItems = Args.GetStringList("remove");
                    if (removeItems != null)
                        Remove(removeItems);

                    string add = Args.GetString("add");
                    if (!string.IsNullOrEmpty(add))
                        AddHead(SanitizePath(add));

                    string append = Args.GetString("append");
                    if (!string.IsNullOrEmpty(append))
                        AddTail(SanitizePath(append));
                }
                catch (SecurityException ex)
                {
                    if (EnvironmentVariableTarget == EnvironmentVariableTarget.Machine)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(resource.IDS_ERR_access_denied);
                        return;
                    }
                    else throw;
                }

                ListPath();
            }
        }
Beispiel #11
0
        public void LoadEnvironment(EnvironmentVariableTarget target)
        {
            VarList.Items.Clear();

            environment = new EnvModel(target);

            foreach (string variable in environment.Variables.Keys)
            {
                VarList.Items.Add(variable);
            }

            SelectVariable(DefaultVariable);
        }
Beispiel #12
0
        public void LoadEnvironment(EnvironmentVariableTarget target)
        {
            VarList.Items.Clear();

            environment = new EnvModel(target);

            foreach (string variable in environment.Variables.Keys)
            {
                VarList.Items.Add(variable);
                environment.Variables[variable].CollectionChanged += new NotifyCollectionChangedEventHandler(Entries_CollectionChanged);
            }

            SelectVariable(DefaultVariable);
        }
        public static string GetVariable(string variable, EnvironmentVariableTarget target = EnvironmentVariableTarget.User)
        {
            string value;
            try
            {
                value = Environment.GetEnvironmentVariable(variable, target);
            }
            catch
            {
                value = null;
            }

            return value;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="EditModel" /> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 /// <param name="target">The target.</param>
 /// <param name="canEditName">if set to <c> true </c> [can edit name].</param>
 /// <param name="canEditValue">if set to <c> true </c> [can edit value].</param>
 /// <param name="canEditTarget">if set to <c> true </c> [can edit target].</param>
 public EditModel(
     string name = EmptyString,
     string value = EmptyString,
     EnvironmentVariableTarget target = EnvironmentVariableTarget.Process,
     bool canEditName = true,
     bool canEditValue = true,
     bool canEditTarget = true)
 {
     this.CanEditName = canEditName;
     this.CanEditValue = canEditValue;
     this.CanEditTarget = canEditTarget;
     this.Value = value;
     this.Name = name;
     this.Target = target;
 }
Beispiel #15
0
        public bool Parse(string[] args)
        {
            Target = EnvironmentVariableTarget.Machine;

            foreach (string arg in args)
            {
                if (arg.StartsWith("-"))
                {
                    switch (arg)
                    {
                        case "-p":
                            Target = EnvironmentVariableTarget.Process;
                            break;

                        case "-m":
                            Target = EnvironmentVariableTarget.Machine;
                            break;

                        case "-u":
                            Target = EnvironmentVariableTarget.User;
                            break;

                        default:
                            Console.WriteLine("Unknown option: {0}", arg);
                            return false;
                    }
                }
                else
                {
                    if (PathSegment == null)
                    {
                        PathSegment = arg;
                    }
                    else
                    {
                        Console.WriteLine("Unknown parameter: {0}", arg);
                        return false;
                    }
                }

            }

            if (PathSegment == null)
            {
                return false;
            }
            return true;
        }
        void __file_env_vars_value(EnvironmentVariableTarget target, string varname)
        {
            lstEnvVarValues.Items.Clear();

            if(varname == null)
                return;

            string value = Environment.GetEnvironmentVariable(varname, target);

            if (value == null)
                return;

            string[] value_split = value.Split(new char[] { ';' });

            foreach (string val in value_split)
            {
                lstEnvVarValues.Items.Add(val);
            }
            return;
        }
        private static void ChangeForTargetEnvironment(Func<IEnumerable<string>, IEnumerable<string>> job, EnvironmentVariableTarget target)
        {
            string psModulePath = Environment.GetEnvironmentVariable(PSModulePathName, target) ?? string.Empty;
            IEnumerable<string> paths = psModulePath.Split(';');
            paths = job(paths);

            if (paths.Count() == 0)
            {
                Environment.SetEnvironmentVariable(PSModulePathName, null, target);
            }
            else if (paths.Count() == 1)
            {
                Environment.SetEnvironmentVariable(PSModulePathName, paths.First(), target);
            }
            else
            {
                psModulePath = string.Join(";", paths.Distinct());
                Environment.SetEnvironmentVariable(PSModulePathName, psModulePath, target);
            }
        }
Beispiel #18
0
		/////////////////////////////////////////////////////////////////////////////

		private static void AddString( string varName, EnvironmentVariableTarget target, string strIn )
		{
			// ******
			string oldValue = Environment.GetEnvironmentVariable( varName, target );
			if( null == oldValue ) {
				oldValue = string.Empty;
			}
			
			// ******
			if( ItemInString(oldValue, strIn) ) {
				//
				// already there
				//
				return;
			}

			// ******
			string newValue = string.Format( "{0}{1}{2}", oldValue, oldValue.EndsWith(";") ? string.Empty : ";", strIn );
			Environment.SetEnvironmentVariable( varName, newValue, target );
		}
Beispiel #19
0
        private static void Add(EnvironmentVariableTarget Target, string NewItem, bool Append)
        {
            if(NewItem == "")
            ShowUse("You must provide a path when using ADD", -1);

              string work = NewItem;
              DirectoryInfo di = null;

              try { di = new DirectoryInfo(NewItem); }
              catch (SystemException se) { ShowError(se, -1); }

              if (di.Exists)
              {
             if(_matchCase)
            {
              string s = GetCaseFromFileSystem(di.FullName);
              if(s != work)
              {
            Verbose("Corrected case: " + s);
            work = s;
              }
            }
              }
              else
              {
            if (!_keepOrphans)
            {
              Console.WriteLine("New path item does not exist, you must set KeepOphans to add it.");
              return;
            }
              }

              List<string> original = GetCurrentPath(Target);

              if (Append)
            original.Add(work);
              else
            original.Insert(0, work);

              UpdatePath(Target, original);
        }
        public InputParameters(string[] args)
        {
            if (args.Length == 0)
            {
                _DisplayUsage = true;

                return;
            }

            for (int _Index = 0; _Index < args.Length; _Index++)
            {
                switch (args[_Index])
                {
                    case "-name":
                    case "/name":
                        this._VariableName = args[++_Index];
                        break;
                    case "-machine":
                    case "/machine":
                        this._VariableScope = EnvironmentVariableTarget.Machine;
                        break;
                    case "-help":
                    case "-?":
                    case "/help":
                    case "/?":
                        this._DisplayUsage = true;
                        break;
                    default:
                        throw new ArgumentException("Invalid parameter specified.", args[_Index]);
                }
            }

            if (!this.DisplayUsage && this.VariableName == String.Empty)
            {
                throw new ArgumentNullException("-name", "You must specify an Environment Variable Name!");
            }
        }
 public async static Task <Dictionary <string, string> > SetEnvironmentVariablesIfNotExistsAsync(string key, string value,
                                                                                                 EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
 {
     return(await Task.Run(() =>
     {
         var res = new Dictionary <string, string>();
         var current = Environment.GetEnvironmentVariable(key);
         if (string.IsNullOrEmpty(current))
         {
             res.Add(key, value);
             SetEnvironmentVariableWithValueReplace(key, value, target);
         }
         return res;
     }));
 }
 public string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
 {
     return(Environment.GetEnvironmentVariable(variable, target));
 }
Beispiel #23
0
        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                SetEnvironmentVariableCore(variable, value);
                return;
            }

#if FEATURE_WIN32_REGISTRY
            if (ApplicationModel.IsUap)
#endif
            {
                // other targets ignored
                return;
            }
#if FEATURE_WIN32_REGISTRY
            // explicitly null out value if is the empty string.
            if (string.IsNullOrEmpty(value) || value[0] == '\0')
            {
                value = null;
            }

            RegistryKey baseKey;
            string      keyName;

            if (target == EnvironmentVariableTarget.Machine)
            {
                baseKey = Registry.LocalMachine;
                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
            }
            else if (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";
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
            }

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

            // send a WM_SETTINGCHANGE message to all windows
            IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST),
                                                         Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);

            Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
#endif // FEATURE_WIN32_REGISTRY
        }
Beispiel #24
0
 public IDictionary <string, string> GetEnvironmentVariables(EnvironmentVariableTarget target)
 {
     throw new NotImplementedException();
 }
Beispiel #25
0
        public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
        {
            ValidateTarget(target);

            return(GetEnvironmentVariablesCore(target));
        }
Beispiel #26
0
 internal static IEnumerable <KeyValuePair <string, string> > EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
 {
     if (target == EnvironmentVariableTarget.Process)
     {
         return(EnumerateEnvironmentVariables());
     }
     return(EnumerateEnvironmentVariablesFromRegistry(target));
 }
Beispiel #27
0
        private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                return GetEnvironmentVariablesCore();
            }
            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);
                    baseKey = Registry.CurrentUser;
                    keyName = @"Environment";
                }

                using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
                {
                    var table = new LowLevelDictionary<string, string>();
                    if (environmentKey != null)
                    {
                        foreach (string name in environmentKey.GetValueNames())
                        {
                            table.Add(name, environmentKey.GetValue(name, "").ToString());
                        }
                    }
                    return table;
                }
            }
        }
 public abstract void AddDirectoryToPath(string directoryPath, EnvironmentVariableTarget target);
	public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) {}
 public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target)
 {
     // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable
     IDictionary vars = Environment.GetEnvironmentVariables(target);
     IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator();
     if (enumerator.MoveNext())
     {
         Assert.IsType<DictionaryEntry>(enumerator.Current);
     }
     else
     {
         Assert.Throws<InvalidOperationException>(() => enumerator.Current);
     }
 }
        public static void SetEnvironmentVariableWithValueReplace(string key, string value, EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
        {
            var valueToSet = ResolveFullValue(value);

            Environment.SetEnvironmentVariable(key, valueToSet, target);
        }
 public static async Task SetEnvironmentVariableWithValueReplaceAsync(string key, string value,
                                                                      EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
 {
     await Task.Run(() => SetEnvironmentVariableWithValueReplace(key, value, target));
 }
 public static void SetEnvironmentVariables(IDictionary <string, string> vars, EnvironmentVariableTarget target = EnvironmentVariableTarget.Process)
 {
     foreach (var var in vars)
     {
         SetEnvironmentVariableWithValueReplace(var.Key, var.Value, target);
     }
 }
Beispiel #34
0
 public IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
 {
     return(System.Environment.GetEnvironmentVariables(target));
 }
 private static void EditPSModulePath(Func <IEnumerable <string>, IEnumerable <string> > job, EnvironmentVariableTarget target)
 {
     ChangeForTargetEnvironment(job, target);
 }
Beispiel #36
0
        // Constructors

        public EnvironmentVariable(string name, string path, EnvironmentVariableTarget type)
        {
            Name = $"%{name}%";
            Path = path;
            Type = type;
        }
        private static void ChangeForTargetEnvironment(Func <IEnumerable <string>, IEnumerable <string> > job, EnvironmentVariableTarget target)
        {
            string psModulePath        = Environment.GetEnvironmentVariable(PSModulePathName, target) ?? string.Empty;
            IEnumerable <string> paths = psModulePath.Split(';');

            paths = job(paths);

            if (paths.Count() == 0)
            {
                Environment.SetEnvironmentVariable(PSModulePathName, null, target);
            }
            else if (paths.Count() == 1)
            {
                Environment.SetEnvironmentVariable(PSModulePathName, paths.First(), target);
            }
            else
            {
                psModulePath = string.Join(";", paths.Distinct());
                Environment.SetEnvironmentVariable(PSModulePathName, psModulePath, target);
            }
        }
 public static string GetEnvironmentVariable(string environmentVariable, EnvironmentVariableTarget target)
 {
     return((!string.IsNullOrEmpty(environmentVariable)
         ? Environment.GetEnvironmentVariable(environmentVariable, target)
         : environmentVariable) !);
 }
Beispiel #39
0
 public EnvironmentVariableOperation(string name, string value, EnvironmentVariableTarget target)
 {
     _name   = name;
     _value  = value;
     _target = target;
 }
Beispiel #40
0
        internal static IEnumerable <KeyValuePair <string, string> > EnumerateEnvironmentVariablesFromRegistry(EnvironmentVariableTarget target)
        {
#if FEATURE_WIN32_REGISTRY
            if (ApplicationModel.IsUap)
#endif
            {
                // Without registry support we have nothing to return
                ValidateTarget(target);
                yield break;
            }
#if FEATURE_WIN32_REGISTRY
            RegistryKey baseKey;
            string      keyName;
            if (target == EnvironmentVariableTarget.Machine)
            {
                baseKey = Registry.LocalMachine;
                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
            }
            else if (target == EnvironmentVariableTarget.User)
            {
                baseKey = Registry.CurrentUser;
                keyName = @"Environment";
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
            }

            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
            {
                if (environmentKey != null)
                {
                    foreach (string name in environmentKey.GetValueNames())
                    {
                        string value = environmentKey.GetValue(name, "").ToString();
                        yield return(new KeyValuePair <string, string>(name, value));
                    }
                }
            }
#endif // FEATURE_WIN32_REGISTRY
        }
 public string GetEnvironmentVariable(string variable, EnvironmentVariableTarget environmentVariableTarget)
 {
     return(System.Environment.GetEnvironmentVariable(variable, environmentVariableTarget));
 }
 public RestApiCredentialsRequest(EnvironmentVariableTarget target = EnvironmentVariableTarget.Machine)
 {
     EnvTarget = target;
 }
Beispiel #43
0
 public void ATTT(EnvironmentVariableTarget environment)
 {
     Console.WriteLine(environment.ToString());
 }
Beispiel #44
0
 public void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
 {
     throw new NotImplementedException();
 }
Beispiel #45
0
        public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
        {
            if (variable == null)
            {
                throw new ArgumentNullException("variable");
            }
            if (variable == String.Empty)
            {
                throw new ArgumentException("String cannot be of zero length.", "variable");
            }
            if (variable.IndexOf('=') != -1)
            {
                throw new ArgumentException("Environment variable name cannot contain an equal character.", "variable");
            }
            if (variable[0] == '\0')
            {
                throw new ArgumentException("The first char in the string is the null character.", "variable");
            }

            switch (target)
            {
            case EnvironmentVariableTarget.Process:
                InternalSetEnvironmentVariable(variable, value);
                break;

            case EnvironmentVariableTarget.Machine:
                if (!IsRunningOnWindows)
                {
                    return;
                }
                using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
                    if (String.IsNullOrEmpty(value))
                    {
                        env.DeleteValue(variable, false);
                    }
                    else
                    {
                        env.SetValue(variable, value);
                    }
                    internalBroadcastSettingChange();
                }
                break;

            case EnvironmentVariableTarget.User:
                if (!IsRunningOnWindows)
                {
                    return;
                }
                using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Environment", true)) {
                    if (String.IsNullOrEmpty(value))
                    {
                        env.DeleteValue(variable, false);
                    }
                    else
                    {
                        env.SetValue(variable, value);
                    }
                    internalBroadcastSettingChange();
                }
                break;

            default:
                throw new ArgumentException("target");
            }
        }
Beispiel #46
0
 /// <summary>
 /// Creates, modifies, or deletes an environment variable stored in the current process or in the Windows operating system registry key reserved for the current user or local machine.
 /// </summary>
 /// <param name="variable">The name of an environment variable.</param>
 /// <param name="value">A value to assign to variable.</param>
 /// <param name="target">Ignored by Bridge. One of the enumeration values that specifies the location of the environment variable.</param>
 public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
 {
     SetEnvironmentVariable(variable, value);
 }
Beispiel #47
0
        public static IEnumerable <KeyValuePair <string, string> > EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                return(EnumerateEnvironmentVariables());
            }

            bool fromMachine = ValidateAndConvertRegistryTarget(target);

            return(EnumerateEnvironmentVariablesFromRegistry(fromMachine: fromMachine));
        }
 private static bool IsSupportedTarget(EnvironmentVariableTarget target)
 {
     return(target == EnvironmentVariableTarget.Process || RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
 }
 public abstract void RemoveDirectoryFromPath(string directoryPath, EnvironmentVariableTarget target);
 public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target)
 {
     // On NetFX, the type returned was always Hashtable
     Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target));
 }
Beispiel #51
0
 private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target) => string.Empty;
        public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target)
        {
            IDictionary results = Environment.GetEnvironmentVariables(target);
            foreach (DictionaryEntry result in results)
            {
                string key = (string)result.Key;
                string value = (string)result.Value ?? string.Empty;

                // Make sure the iterated value we got matches the one we get explicitly
                Assert.NotNull(result.Key as string);
                Assert.Equal(value, Environment.GetEnvironmentVariable(key, target));

                try
                {
                    // Change it to something else.  Not all values can be changed and will silently
                    // not change, so we don't re-check and assert for equality.
                    Environment.SetEnvironmentVariable(key, value + "changed", target);
                }
                finally
                {
                    // Change it back
                    Environment.SetEnvironmentVariable(key, value, target);
                }
            }
        }
Beispiel #53
0
 private static IDictionary GetEnvironmentVariablesCore(EnvironmentVariableTarget target) => new LowLevelDictionary <string, string>();
Beispiel #54
0
        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.mincore.SendMessageTimeout(
            //    new IntPtr(Interop.mincore.HWND_BROADCAST), Interop.mincore.WM_SETTINGCHANGE,
            //    IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
        }
Beispiel #55
0
 private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
 {
     throw new PlatformNotSupportedException();
 }
Beispiel #56
0
		public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
		{
			if (variable == null)
				throw new ArgumentNullException ("variable");
			if (variable == String.Empty)
				throw new ArgumentException ("String cannot be of zero length.", "variable");
			if (variable.IndexOf ('=') != -1)
				throw new ArgumentException ("Environment variable name cannot contain an equal character.", "variable");
			if (variable[0] == '\0')
				throw new ArgumentException ("The first char in the string is the null character.", "variable");

			switch (target) {
			case EnvironmentVariableTarget.Process:
				InternalSetEnvironmentVariable (variable, value);
				break;
			case EnvironmentVariableTarget.Machine:
				if (!IsRunningOnWindows)
					return;
				using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
					if (String.IsNullOrEmpty (value))
						env.DeleteValue (variable, false);
					else
						env.SetValue (variable, value);
					internalBroadcastSettingChange ();
				}
				break;
			case EnvironmentVariableTarget.User:
				if (!IsRunningOnWindows)
					return;
				using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", true)) {
					if (String.IsNullOrEmpty (value))
						env.DeleteValue (variable, false);
					else
						env.SetValue (variable, value);
					internalBroadcastSettingChange ();
				}
				break;
			default:
				throw new ArgumentException ("target");
			}
		}
 public static void RemoveModuleFromPSModulePath(string modulePath, EnvironmentVariableTarget target)
 {
     EditPSModulePath(list => list.Where(p => !p.Equals(modulePath, StringComparison.OrdinalIgnoreCase)), target);
 }
Beispiel #58
0
		public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
		{
			switch (target) {
			case EnvironmentVariableTarget.Process:
				return GetEnvironmentVariable (variable);
			case EnvironmentVariableTarget.Machine:
				new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
				if (!IsRunningOnWindows)
					return null;
				using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
					object regvalue = env.GetValue (variable);
					return (regvalue == null) ? null : regvalue.ToString ();
				}
			case EnvironmentVariableTarget.User:
				new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
				if (!IsRunningOnWindows)
					return null;
				using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", false)) {
					object regvalue = env.GetValue (variable);
					return (regvalue == null) ? null : regvalue.ToString ();
				}
			default:
				throw new ArgumentException ("target");
			}
		}
Beispiel #59
0
		public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
		{
			IDictionary variables = (IDictionary)new Hashtable ();
			switch (target) {
			case EnvironmentVariableTarget.Process:
				variables = GetEnvironmentVariables ();
				break;
			case EnvironmentVariableTarget.Machine:
				new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
				if (IsRunningOnWindows) {
					using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
						string[] value_names = env.GetValueNames ();
						foreach (string value_name in value_names)
							variables.Add (value_name, env.GetValue (value_name));
					}
				}
				break;
			case EnvironmentVariableTarget.User:
				new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
				if (IsRunningOnWindows) {
					using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment")) {
						string[] value_names = env.GetValueNames ();
						foreach (string value_name in value_names)
							variables.Add (value_name, env.GetValue (value_name));
					}
				}
				break;
			default:
				throw new ArgumentException ("target");
			}
			return variables;
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="EnvVarSetting" /> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 /// <param name="myTarget">My target.</param>
 public EnvVarSetting(
     string name = EmptyString,
     string value = EmptyString,
     EnvironmentVariableTarget myTarget = EnvironmentVariableTarget.Process)
 {
     this.name = name;
     this.value = value;
     Target = myTarget;
 }