开发背景
在 Windows 系统应用开发与部署中,环境变量 PATH
对查找可执行文件和库文件很重要。手动添加新路径到 PATH
繁琐易错,在多用户环境下还会影响系统稳定性。
因此,开发了一个自动化函数用于向用户级 PATH
添加新路径。因修改需管理员权限,该函数会检查权限,同时避免重复添加,以提高效率和系统可维护性、可扩展性,方便软件安装更新等操作。
功能实现
C#实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| private bool AddUserEnvironmentVariable(string targetPath) { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new(identity); if(!principal.IsInRole(WindowsBuiltInRole.Administrator)) return false; string currentPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User); if (!currentPath.Contains(targetPath)) { string updatedPath = currentPath + ";" + targetPath; Environment.SetEnvironmentVariable("PATH", updatedPath, EnvironmentVariableTarget.User); return true; } return false; }
|
python实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| def add_user_environment_variable(target_path): try: is_admin = os.getuid() == 0 except AttributeError: import ctypes is_admin = ctypes.windll.shell32.IsUserAnAdmin()!= 0 if not is_admin: return False path_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Environment", 0, winreg.KEY_ALL_ACCESS) current_value, type_ = winreg.QueryValueEx(path_key, "Path") if target_path not in current_value.split(os.pathsep): updated_value = current_value + os.pathsep + target_path winreg.SetValueEx(path_key, "Path", 0, winreg.REG_EXPAND_SZ, updated_value) return True return False
|