在.NET中获取远程计算机上环境变量的真实值 [英] Get the real values of environment variables on a remote machine in .NET

查看:111
本文介绍了在.NET中获取远程计算机上环境变量的真实值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取环境变量实际值.

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%:

    HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRoot

    select windowsdirectory from Win32_OperatingSystem

  • 可以通过检查%SystemRoot%

    来确定
  • %SystemDrive%

诸如%AppData%之类的变量取决于用户,可以在

HKEY_USERS\<user SID>\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\AppData

下找到

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\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

这篇关于在.NET中获取远程计算机上环境变量的真实值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆