Getting and setting the user and system environment variables #64

This tip informs how to read environment variables for either the user or the system. It also shows how to permanently update system and user environment variables.

function GetEnvVariable(Name: string; User: Boolean = True): string;
var
  Str: array[0..255] of char;
begin
  with TRegistry.Create do
  try
    if User then
    begin
      RootKey := HKEY_CURRENT_USER;
      //OpenKey('Environment', False);
      OpenKeyReadOnly('Environment', False);
    end
    else
    begin
      RootKey := HKEY_LOCAL_MACHINE;
      //OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
      //  'Manager\Environment', False);
      OpenKeyReadOnly('SYSTEM\CurrentControlSet\Control\Session ' +
        'Manager\Environment', False);
    end;
    Result := ReadString(Name);
    ExpandEnvironmentStrings(PChar(Result), Str, 255);
    Result := Str;
  finally
    Free;
  end;
end;

procedure SetEnvVariable(Name, Value: string; User: Boolean = True);
var
  rv: DWORD;
begin
  with TRegistry.Create do
  try
    if User then
    begin
      RootKey := HKEY_CURRENT_USER;
      OpenKey('Environment', False);
      WriteString(Name, Value);
    end
    else
    begin
      RootKey := HKEY_LOCAL_MACHINE;
      OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
        'Manager\Environment', False);
    end;
    WriteString(Name, Value);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
      (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
  finally
    Free;
  end;
end;

On Windows NT, 2000, XP or Vista attempting to write system environment variables will require the user to have administrative privileges.

Note the change to use OpenKeyReadOnly rather than OpenKey in GetEnvVariable. This was done to avoid needing registry write permissions.

Author: Joe Donth
Contributor: Joe Donth
Added: 2008/04/12
Last updated: 2008/04/12