[C#]解决C#读取环境变量导致%变量会自动替换成绝对路径问题

1.用 RegistryValueOptions.DoNotExpandEnvironmentNames

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

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);

【参考文献】

https://www.52pojie.cn/forum.php?mod=viewthread&tid=1798986 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农张三疯

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值