有的时候我们需要将exe所在目录添加环境变量,这样可以在cmd中直接调用此exe,方法如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using Microsoft.Win32; 7 using System.Diagnostics; 8 using System.Runtime.InteropServices; 9 10 namespace AppGet { 11 class Program { 12 static void Main(string[] args) { 13 Register(); 14 15 Console.WriteLine("press any key to exit."); 16 Console.ReadLine(); 17 } 18 19 private static void Register() { 20 RegistryKey systemPathKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true); 21 22 if (string.IsNullOrEmpty(systemPathKey.GetValue("AppGet", string.Empty).ToString())) { 23 systemPathKey.SetValue("AppGet", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName), RegistryValueKind.String); 24 } 25 26 string path = systemPathKey.GetValue("Path", "Empty", RegistryValueOptions.DoNotExpandEnvironmentNames).ToString(); 27 if (!path.ToLower().Contains(@"%appget%")) { 28 systemPathKey.SetValue("Path", @"%AppGet%;" + path, RegistryValueKind.ExpandString); 29 } 30 31 int rtnVal = 0; 32 SendMessageTimeoutA(HWND_BROADCAST, WM_SETTINGCHANGE, 0, "Environment", 2, 5000, rtnVal); 33 } 34 35 private const int HWND_BROADCAST = 0xffff; 36 private const int WM_WININICHANGE = 0x001a, WM_SETTINGCHANGE = WM_WININICHANGE, INI_INTL = 1; 37 [DllImport("user32.dll")] 38 private static extern int SendMessageTimeoutA(int hWnd, uint wMsg, uint wParam, string lParam, int fuFlags, int uTimeout, int lpdwResult); 39 } 40 }
说明:
1. 22行的AppGet为系统变量名(下同)
2. 26行GetValue必须指定RegistryValueOptions.DoNotExpandEnvironmentNames,否则在接下来的SetValue会将系统Path中的的变量全部替换掉。
3. 28行SetValue必须指定RegistryValueKind.ExpandString,否则系统会把%AppGet%当成普通字符串,而不是变量。
4. 32的SendMessageTimeoutA作用为广播上面的设置,这样就不需要注销或重启系统了。
5. 之前也尝试过用Environment.SetEnvironmentVariable和Environment.GetEnvironmentVariable,后来发现GetEnvironmentVariable方法没有DoNotExpandEnvironmentNames这样的参数,所以会将系统Path中的的变量全部替换掉!
6. 在测试之前最好先备份下注册表。