我试图获得环境变量的实际值。
这是我目前所看到的:
string query = string.Format("Select VariableValue From Win32_Environment Where Name = '{0}'", variableName);
using (var searcher = new ManagementObjectSearcher(query))
using (ManagementObject result = searcher.Get().Cast<ManagementObject>().FirstOrDefault())
{
if (result != null)
return Convert.ToString(result["VariableValue"]);
}
可以工作,但这里有问题:传递'windir'作为名称将'%SystemRoot%'作为值。我真正想要的是的实际路径,即"C: Windows"。
我尝试使用递归来获取'SystemRoot'的值,但是没有找到匹配。
我如何确保真实值得到返回?
谢谢!
对于系统路径变量(如%SystemRoot%
),没有方便的方法。
您必须通过读取相应的注册表值来查找这些值。以下是其中一些系统变量的(不完整)列表:
-
%SystemRoot%:
HKLMSOFTWAREMicrosoftWindows NTCurrentVersionSystemRoot
orselect windowsdirectory from Win32_OperatingSystem
-
%SystemDrive%可以通过检查%SystemRoot%
来确定
像%AppData%这样的变量是用户依赖的,可以在
HKEY_USERS我知道这是最好的创意,但这似乎是最简单的解决方案:
也许太多的开销?using (var process = new Process()) { process.StartInfo.FileName = @"C:PsToolsPsExec.exe"; process.StartInfo.Arguments = @"\machineName cmd /c echo " + environmentVar; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); return process.StandardOutput.ReadToEnd(); }
你不能使用Win32_Environment,但是你可以使用远程注册表。
RegistryKey environmentKey = RegistryKey.OpenRemoteBaseKey(
RegistryHive.LocalMachine, "\server");
RegistryKey key = environmentKey.OpenSubKey(
@"SYSTEMCurrentControlSetControlSession ManagerEnvironment", false);
string value = (string)key.GetValue("System");
使用Environment.GetFolderPath(Environment.SpecialFolder.System)