PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable()

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

问题描述

我想用 C# 程序扩展当前的 PATH 变量.这里我有几个问题:

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

  1. 使用GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)替换占位符(即'%SystemRoot%system32'替换为当前路径<代码>'C:Windowssystem32').更新PATH变量,我不想用路径替换占位符.

  1. 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)