GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable

后端 未结 6 1650

I want to extend the current PATH variable with a C# program. Here I have several problems:

  1. Using GetEnvironmentVariable(\"PATH\", EnvironmentVariable

6条回答
  •  一整个雨季
    2020-12-11 15:38

    You could try this mix. It gets the Path variables from the registry, and adds the "NewPathEntry" to Path, if not already there.

    static void Main(string[] args)
        {
            string NewPathEntry = @"%temp%\data";
            string NewPath = "";
            bool MustUpdate = true;
            string RegKeyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
            string path = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey(RegKeyName).GetValue
                ("Path", "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames);
            string[] paths = path.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string subPath in paths)
            {
                NewPath += subPath + ";";
                if (subPath.ToLower() == NewPathEntry.ToLower())
                {
                    MustUpdate = false;
                }
            }
            if (MustUpdate == true)
            {
                Environment.SetEnvironmentVariable("Path", NewPath + NewPathEntry, EnvironmentVariableTarget.Machine);
            }
        }
    

提交回复
热议问题