GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable

后端 未结 6 1652

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:36

    Using Registry.GetValue will expand the placeholders, so I recommend using Registry.LocalMachine.OpenSubKey, then get the value from the sub key with options set to not expand environment variables. Once you've manipulated the path to your liking, use the registry to set the value again. This will prevent Windows "forgetting" your path as you mentioned in the second part of your question.

    const string pathKeyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
    var pathKey = Registry.LocalMachine.OpenSubKey(pathKeyName);
    var path = (string)pathKey.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
    // Manipulate path here, storing in path
    Registry.SetValue(String.Concat(@"HKEY_LOCAL_MACHINE\", pathKeyName), "PATH", path);
    

提交回复
热议问题