c# - 获取文字系统变量路径
问题描述
有没有办法将路径环境变量作为文字字符串而不是展开?
IE
%systemroot%\System32;%systemroot%\;etc...
代替
C:\Windows\System32;C:\Windows\;etc...
我试过使用
Environment.GetSystemVariable("Path");
但这给了我扩展的目录,并且我在 Environment 下看不到任何其他可以让我得到它的东西。
编辑:
PathUnExpandEnvStrings
仅当整个路径是环境变量时才有效。
IE
C:\Windows\System32;C:\Windows;etc...
变成
C:\Windows\System32;%systemroot%;etc...
使用
Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", "Path", null);
仍然得到值C:\Windows\System32;C:\Windows;etc...
解决方案
如果你去注册表路由,你可以传递RegistryValueOptions.DoNotExpandEnvironmentNames
给RegistryKey.GetValue()
实例方法来获取未扩展的路径......
using System;
using Microsoft.Win32;
namespace SO60725684
{
class Program
{
static void Main()
{
const string environmentKeyPath = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
const string valueName = "TEMP";
using (RegistryKey environmentKey = Registry.LocalMachine.OpenSubKey(environmentKeyPath))
{
foreach (RegistryValueOptions options in Enum.GetValues(typeof(RegistryValueOptions)))
{
object valueData = environmentKey.GetValue(valueName, "<default>", options);
Console.WriteLine($"{valueName} ({options}) = \"{valueData}\"");
}
}
}
}
}
这印...
Temp (None) = "C:\WINDOWS\TEMP"
Temp (DoNotExpandEnvironmentNames) = "%SystemRoot%\TEMP"
我使用该"TEMP"
变量只是为了简化它的值,但它同样适用于"Path"
.
如果您不想依赖环境变量的后备存储,还有一个Win32_Environment
管理类可以在不扩展的情况下公开值...
using System;
using System.Management;
namespace SO60725684
{
class Program
{
static void Main()
{
string[] propertiesToDisplay = new string[] { "Name", "SystemVariable", "UserName", "VariableValue" };
ObjectQuery query = new SelectQuery("Win32_Environment", "Name = 'TEMP'", propertiesToDisplay);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection resultCollection = searcher.Get())
{
foreach (ManagementBaseObject resultInstance in resultCollection)
{
PropertyDataCollection properties = resultInstance.Properties;
foreach (string propertyName in propertiesToDisplay)
{
PropertyData property = properties[propertyName];
Console.WriteLine($"{property.Name}: {property.Value}");
}
Console.WriteLine();
}
}
}
}
}
这印...
Name: TEMP
SystemVariable: True
UserName: <SYSTEM>
VariableValue: %SystemRoot%\TEMP
Name: TEMP
SystemVariable: False
UserName: NT AUTHORITY\SYSTEM
VariableValue: %USERPROFILE%\AppData\Local\Temp
Name: TEMP
SystemVariable: False
UserName: ComputerName\UserName
VariableValue: %USERPROFILE%\AppData\Local\Temp
如您所见,当为多个用户定义变量时,您会得到多个结果,因此您需要对SystemVariable
和UserName
属性进行进一步过滤以获得您想要的结果。
推荐阅读
- string - 有没有办法在 C++ 中比较字符和字符串?
- python - 非贪心通配符出现贪心匹配?
- python - 如何完全删除文本文件的第一行?
- google-cloud-platform - 从控制台与命令行获取不同的 id - 在 Google Compute (GCP) 中推荐的身份管理?
- nearprotocol - create_account 函数:--masterAccount 参数说明
- python - 从主函数/类外部更新 tkinter 进度条
- excel - 如果单元格值等于“”,如何编写 Excel 宏以删除整行
- arrays - Laravel - 在字符串上调用成员函数 save()
- javascript - 卸载的组件仍然首先渲染
- python - 如何从 Python 中此对象返回的字典中访问特定值