windows PATH 变量的 GetEnvironmentVariable() 和 SetEnvironmentVariable()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7121846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GetEnvironmentVariable() and SetEnvironmentVariable() for PATH Variable
提问by Freddy
I want to extend the current PATH variable with a C# program. Here I have several problems:
我想用 C# 程序扩展当前的 PATH 变量。这里我有几个问题:
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.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:
Using
GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine)
替换占位符(即被'%SystemRoot%\system32'
当前路径替换'C:\Windows\system32'
)。更新 PATH 变量,我不想用路径替换占位符。在
SetEnvironmentVariable
没有程序无法再从命令框中打开之后(即命令框中的 calc.exe 不起作用)。我使用以下代码:
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)
PATH
使用 Windows编辑和更改变量后,一切正常。(我的东西需要修改,否则不会被覆盖)
回答by Sabri Sawaad
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);
回答by Strillo
You can use WMI to retrieve the raw values (not sure about updating them though):
您可以使用 WMI 来检索原始值(但不确定是否更新它们):
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Environment WHERE Name = 'PATH'");
foreach (ManagementBaseObject managementBaseObject in searcher.Get())
Console.WriteLine(managementBaseObject["VariableValue"]);
Check WMI Referenceon MSDN
检查MSDN 上的WMI 参考
回答by Daro
You could try this mix. It gets the Path variables from the registry, and adds the "NewPathEntry" to Path, if not already there.
你可以试试这个组合。它从注册表中获取 Path 变量,并将“NewPathEntry”添加到 Path(如果还没有)。
static void Main(string[] args)
{
string NewPathEntry = @"%temp%\data";
string NewPath = "";
bool MustUpdate = true;
string RegKeyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
string path = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey(RegKeyName).GetValue
("Path", "", Microsoft.Win32.RegistryValueOptions.DoNotExpandEnvironmentNames);
string[] paths = path.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string subPath in paths)
{
NewPath += subPath + ";";
if (subPath.ToLower() == NewPathEntry.ToLower())
{
MustUpdate = false;
}
}
if (MustUpdate == true)
{
Environment.SetEnvironmentVariable("Path", NewPath + NewPathEntry, EnvironmentVariableTarget.Machine);
}
}
回答by Isaac Overacker
Using Registry.GetValue
will expand the placeholders, so I recommend using Registry.LocalMachine.OpenSubKey
, then get the value from the sub key with options set to not expand environment variables. Once you've manipulated the path to your liking, use the registry to set the value again. This will prevent Windows "forgetting" your path as you mentioned in the second part of your question.
UsingRegistry.GetValue
将扩展占位符,所以我建议使用Registry.LocalMachine.OpenSubKey
,然后从子键中获取值,并将选项设置为不扩展环境变量。根据自己的喜好操作路径后,请使用注册表再次设置该值。这将防止 Windows“忘记”您在问题第二部分中提到的路径。
const string pathKeyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
var pathKey = Registry.LocalMachine.OpenSubKey(pathKeyName);
var path = (string)pathKey.GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
// Manipulate path here, storing in path
Registry.SetValue(String.Concat(@"HKEY_LOCAL_MACHINE\", pathKeyName), "PATH", path);
回答by Andy Christianson
You could go through the registry...
你可以通过注册表...
string keyName = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
//get raw PATH environment variable
string path = (string)Registry.GetValue(keyName, "Path", "");
//... Make some changes
//update raw PATH environment variable
Registry.SetValue(keyName, "Path", path);
回答by Dalibor ?arapi?
While working on the application we had to have an option to use Oracle instantclient from user-defined folder. In order to use the instantclient we had to modify the environment path variable and add this folder beforecalling any Oracle related functionality. Here is method that we use for that:
在处理应用程序时,我们必须选择从用户定义的文件夹中使用 Oracle 即时客户端。为了使用即时客户端,我们必须在调用任何 Oracle 相关功能之前修改环境路径变量并添加此文件夹。这是我们使用的方法:
/// <summary>
/// Adds an environment path segments (the PATH varialbe).
/// </summary>
/// <param name="pathSegment">The path segment.</param>
public static void AddPathSegments(string pathSegment)
{
LogHelper.Log(LogType.Dbg, "EnvironmentHelper.AddPathSegments", "Adding path segment: {0}", pathSegment);
string allPaths = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process);
if (allPaths != null)
allPaths = pathSegment + "; " + allPaths;
else
allPaths = pathSegment;
Environment.SetEnvironmentVariable("PATH", allPaths, EnvironmentVariableTarget.Process);
}
Note that this has to be called before anything else, possibly as the first line in your Main file (not sure about console applications).
请注意,这必须在其他任何事情之前调用,可能作为主文件中的第一行(不确定控制台应用程序)。