GetEnvironmentVariable()和SetEnvironmentVariable方法()的路径变量变量、路径、方法、GetEnvironmentVariable

2023-09-03 04:44:25 作者:感情影响拔刀

我想目前PATH变量与C#程序扩展。在这里,我有几个问题:

使用 GetEnvironmentVariable(PATH,EnvironmentVariableTarget.Machine)替换占位符(即%SYSTEMROOT%\ SYSTEM32将被替换为当前路径C:\ WINDOWS \ SYSTEM32)。更新PATH变量,我不想替换路径的占位符。

SetEnvironmentVariable方法没有程序不能在命令中打开了(即CALC.EXE在命令框不工作)。使用下面的code林:

 字符串oldPath = Environment.GetEnvironmentVariable(PATH,EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable(PATH,oldPath +;%MYDIR%,EnvironmentVariableTarget.Machine);
 

编辑和修改 PATH后与Windows一切都变的作品了。 (我的事情的变化是必需的,否则是不会被覆盖)

解决方案

您可以使用注册表来读取和更新:

 字符串的keyName = @系统\ CurrentControlSet \控制\会话管理器\环境;
//获取非扩展PATH环境变量
字符串oldPath =(字符串)Registry.LocalMachine.CreateSubKey(注册表项目).GetValue(路径,,RegistryValueOptions.DoNotExpandEnvironmentNames);

//设置路径作为一个可扩展的字符串
Registry.LocalMachine.CreateSubKey(注册表项目).SetValue(路径,oldPath +;%MYDIR%,RegistryValueKind.ExpandString);
 

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

Using GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine) replaces the placeholders (i.e. '%SystemRoot%\system32' is replaced by the current path 'C:\Windows\system32'). Updating the PATH variable, I dont want to replace the placeholder with the path.

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);

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 = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
//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);