GetEnvironmentVariable()和SetEnvironmentVariable方法()的路径变量 [英] GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable

查看:2716
本文介绍了GetEnvironmentVariable()和SetEnvironmentVariable方法()的路径变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  2. 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:

  1. 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.

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

这篇关于GetEnvironmentVariable()和SetEnvironmentVariable方法()的路径变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆