问题描述
我想用 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)