I'm trying to get the actual values of environment variables.
This is what I have so far:
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"]);
}
That works, but here's the problem: passing 'windir' as name gets '%SystemRoot%' as value. What I really want is the actual path, i.e. 'C:\Windows'.
I tried using recursion to get the value of 'SystemRoot' but no matches were found.
How can I make sure that the real values get returned?
Thx!
For system path variables (like %SystemRoot%
) there's no convenient way.
You have to look for these values yourself by reading the corresponding registry values. Heres' a (not complete) list of some of these system variables:
%SystemRoot%:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRootor
select windowsdirectory from Win32_OperatingSystem
%SystemDrive% can be determined by examining %SystemRoot%
Variables like %AppData% are user dependent and found under
HKEY_USERS\<user SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\AppData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With