...retrieve Environmental Variables as strings by name?

Author: Biopsy

Category: System

{ This code is very useful if you need to "translate" various
environmental variables. I use this a lot to get paths to TEMP
or windows folders on different systems.}

function GetEnvVarValue(const VarName: string): string;
var
  
BufSize: Integer;  // buffer size required for value
begin
  
// Get required buffer size (inc. terminal #0)
  
BufSize := GetEnvironmentVariable(PChar(VarName), nil, 0);
  if BufSize > 0 then
  begin
    
// Read env var value into result string
    
SetLength(Result, BufSize - 1);
    GetEnvironmentVariable(PChar(VarName),
      PChar(Result), BufSize);
  end
  else
    
// No such environment variable
    
Result := '';
end;

procedure TForm1.Button1(Sender: TObject);
begin
  
ShowMessage(GetEnvVarValue('SystemRoot'));
end;

{--- Here is the list of different variables you could use -----------
ALLUSERSPROFILE
APPDATA
CLIENTNAME
CommonProgramFiles
COMPUTERNAME
ComSpec
HOMEDRIVE
HOMEPATH
LOGONSERVER
NUMBER_OF_PROCESSORS
OS
Path
PATHEXT
PCToolsDir
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
ProgramFiles
SESSIONNAME
SystemDrive
SystemRoot
TEMP
TMP
USERDOMAIN
USERNAME
USERPROFILE
windir
---------------------------------------------------------------------}

 

printed from
www.swissdelphicenter.ch
developers knowledge base