本帖最后由 pjy612 于 2023-6-18 22:29 编辑
1.用 RegistryValueOptions.DoNotExpandEnvironmentNames
[C#] 纯文本查看 复制代码 static string GetRawEnvironmentVariableValue2(string variableName)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"))
{
if (key != null)
{
object value = key.GetValue(variableName, null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (value != null)
{
return value.ToString();
}
}
}
return null;
}
2.用底层API
[C#] 纯文本查看 复制代码 static string GetRawEnvironmentVariableValue(string variableName)
{
const int REG_EXPAND_SZ = 0x0002;
const int KEY_QUERY_VALUE = 0x0001;
const int ERROR_SUCCESS = 0;
IntPtr hKey = IntPtr.Zero;
int result = RegOpenKeyEx(RegistryHive.LocalMachine, @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", 0, KEY_QUERY_VALUE, out hKey);
if (result != ERROR_SUCCESS)
{
return null;
}
StringBuilder buffer = new StringBuilder(1024);
int bufferSize = buffer.Capacity * sizeof(char);
result = RegQueryValueEx(hKey, variableName, IntPtr.Zero, out int lpType, buffer, ref bufferSize);
RegCloseKey(hKey);
if (result != ERROR_SUCCESS)
{
return null;
}
if (lpType == REG_EXPAND_SZ)
{
return buffer.ToString();
}
return null;
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int RegOpenKeyEx(RegistryHive hKey, string lpSubKey, int ulOptions, int samDesired, out IntPtr phkResult);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int RegCloseKey(IntPtr hKey);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int RegQueryValueEx(IntPtr hKey, string lpValueName, IntPtr lpReserved, out int lpType, StringBuilder lpData, ref int lpcbData);
|