GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable(PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable())
问题描述
我想用 C# 程序扩展当前的 PATH 变量.这里我有几个问题:
I want to extend the current PATH variable with a C# program. Here I have several problems:
使用
GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)替换占位符(即
).更新PATH变量,我不想用路径替换占位符.'%SystemRoot%system32'
替换为当前路径<代码>'C:Windowssystem32'
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable()


- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01