PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable()

6

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14