我想用 C# 程序扩展当前的 PATH 变量.这里我有几个问题:
I want to extend the current PATH variable with a C# program. Here I have several problems:
使用GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)
替换占位符(即'%SystemRoot%system32'
替换为当前路径<代码>'C:Windowssystem32').更新PATH变量,我不想用路径替换占位符.
Using GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)
replaces the placeholders (i.e. '%SystemRoot%system32'
is replaced by the current path 'C:Windowssystem32'
). Updating the PATH variable, I dont want to replace the placeholder with the path.
SetEnvironmentVariable
之后,无法再从命令框中打开任何程序(即命令框中的 calc.exe 不起作用).我使用以下代码:
After SetEnvironmentVariable
no program can't be opened from the command box anymore (i.e. calc.exe in the command box doesn't work). Im using following code:
String oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", oldPath + ";%MYDIR%", EnvironmentVariableTarget.Machine);
在使用 Windows 编辑和更改 PATH
变量后,一切都会再次运行.(我的东西需要改变,否则不会被覆盖)
After editing and changing the PATH
variable with Windows everything works again. (I thing changes are required, otherwise it is not overwritten)
可以使用注册表读取更新:
You can use the registry to read and update:
string keyName = @"SYSTEMCurrentControlSetControlSession ManagerEnvironment";
//get non-expanded PATH environment variable
string oldPath = (string)Registry.LocalMachine.CreateSubKey(keyName).GetValue("Path", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
//set the path as an an expandable string
Registry.LocalMachine.CreateSubKey(keyName).SetValue("Path", oldPath + ";%MYDIR%", RegistryValueKind.ExpandString);
这篇关于PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!