Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the real values of environment variables on a remote machine in .NET

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!

like image 478
David Avatar asked Aug 29 '11 13:08

David


1 Answers

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\SystemRoot
    or
    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
like image 107
VVS Avatar answered Nov 02 '22 10:11

VVS