Skip over navigation

How to access environment variables


Why this article?

Sometimes we need to access some system configuration information that is stored in environment variables – such as the search path. These are stored in environment variables.

On other occasions we might want to provide a spawned application with some global information using environment variables.

The purpose of this article is to explain how to read existing environment variables and how to set up new environment variables to pass to other processes.

A little background information

Before we jump into writing some code to access and update environment variables, let us take a brief look at how Windows handles them.

When Windows starts a program it provides the program with a copy of its environment variables. The API functions that work with environment variables operate on this copy, not on the original environment variables. This means that any changes you make to environment variables within the program only apply to the program's copy and do not update the underlying Window's environment variables – such changes are lost when your program terminates.

Any child process started by your application gets, by default, a copy of your program's current environment, not that of Windows. This means that any changes you make to the environment before starting the child process are reflected in the child's own environment block. This default behaviour can be overridden by defining a custom block of environment variables to be passed to the child process. We discuss how to do this below.

One final point to note is that the block of memory allocated for environment variables is a fixed size. This means that you can't keep adding new environment variables to the block without limit. At some point the attempt to add a variable, or to store more data in an existing one, will fail. The size of the block created for a process depends on the number of environment variables and the size of the data to be passed to it. Back in the days of Windows 98 the block size was small (about 16Kb) and was incremented in 4Kb chunks. On modern Windows systems this size is massively increased.

How it's done

Now we have an understanding of how Windows handles environment variables, let us move on to look at how we work with them. Windows provides four API functions for accessing and updating environment variables:

  1. GetEnvironmentVariable
    Returns the value of a given environment variable.
  2. SetEnvironmentVariable
    Sets an environment variable's value, creating a new variable if necessary. This routine can also be used to delete an environment variable.
  3. GetEnvironmentStrings
    Gets a list of all the environment variables available to a process.
  4. ExpandEnvironmentStrings
    Replaces environment variables delimited by "%" characters in a string with the variable's value.

We will develop six Delphi routines: five that wrap these API calls plus one that can be used to create a new environment block for passing to a child process. They are:

  1. GetEnvVarValue
    Returns the value of a given environment variable.
  2. SetEnvVarValue
    Sets the value of the given environment variable.
  3. DeleteEnvVar
    Deletes the given environment variable.
  4. GetAllEnvVars
    Fills a string list with the names and values of all the program's environment variables.
  5. ExpandEnvVars
    Replaces all "%" delimited environment variables in a string with their values.
  6. CreateEnvBlock
    Creates a new environment block suitable for passing to a child process.

And so to the code:


This routine returns the value of a given environment variable (or returns the empty string if there is no variable with that name). Here's the definition:

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

You'll notice that GetEnvironmentVariable is called twice: once to get the size of the required buffer and the second time to actually read the variable. This is a common Windows idiom.

Back to list


This routine sets the value of an environment variable. If the variable doesn't already exist it is created. Zero is returned if all goes well, otherwise a Windows error code is returned. An error may occur if there is no room in the environment block for the new value. The implementation is very simple:

function SetEnvVarValue(const VarName,
  VarValue: string): Integer;
  // Simply call API function
  if SetEnvironmentVariable(PChar(VarName),
    PChar(VarValue)) then
    Result := 0
    Result := GetLastError;
Listing 2

Back to list


This routine deletes the given environment variable. Note that SetEnvVarValue('') has the same effect. Zero is returned on success and a Windows error code on error. The implementation is again simple:

function DeleteEnvVar(const VarName: string): Integer;
  if SetEnvironmentVariable(PChar(VarName), nil) then
    Result := 0
    Result := GetLastError;
Listing 3

Back to list


This routine returns all of a program's environment variables in a string list. Each entry in the list is of the form Name=Value. You can use the TStrings Names[] and Values[] properties to extract the variable names and value from the string. The function returns the amount of space taken by the strings in the environment block. If you just want to know the size of the environment variables, pass a nil parameter. Here's the definition:

function GetAllEnvVars(const Vars: TStrings): Integer;
  PEnvVars: PChar;    // pointer to start of environment block
  PEnvEntry: PChar;   // pointer to an env string in block
  // Clear the list
  if Assigned(Vars) then
  // Get reference to environment block for this process
  PEnvVars := GetEnvironmentStrings;
  if PEnvVars <> nil then
    // We have a block: extract strings from it
    // Env strings are #0 separated and list ends with #0#0
    PEnvEntry := PEnvVars;
      while PEnvEntry^ <> #0 do
        if Assigned(Vars) then
        Inc(PEnvEntry, StrLen(PEnvEntry) + 1);
      // Calculate length of block
      Result := (PEnvEntry - PEnvVars) + 1;
      // Dispose of the memory block
    // No block => zero length
    Result := 0;
Listing 4

Back to list


This function takes as a parameter a string of text containing one or more environment variables, delimited by "%" characters, and returns the string with each environment variable replaced by its value.

For example, if we have two environment variables ME and YOU set to "Peter" and "Gloria" respectively then

ExpandEnvVars('%ME% say hello to %YOU%');


Peter say hello to Gloria
function ExpandEnvVars(const Str: string): string;
  BufSize: Integer; // size of expanded string
  // Get required buffer size 
  BufSize := ExpandEnvironmentStrings(
    PChar(Str), nil, 0);
  if BufSize > 0 then
    // Read expanded string into result string
    SetLength(Result, BufSize - 1);
      PChar(Result), BufSize);
    // Trying to expand empty string
    Result := '';
Listing 5

Back to list


This final function creates an environment block that can be passed to a child process.

It creates a new environment block containing the strings from the NewEnv string list. If IncludeCurrent is true then the variables defined in the current process' environment block are included. The new block is stored in the memory pointed to by Buffer, which must be at least BufSize characters. The size of the block is returned. If the provided buffer is nil or is too small then no block is created. The return value gives the required buffer size in characters.

function CreateEnvBlock(const NewEnv: TStrings;
  const IncludeCurrent: Boolean;
  const Buffer: Pointer;
  const BufSize: Integer): Integer;
  EnvVars: TStringList; // env vars in new block
  Idx: Integer;         // loops thru env vars
  PBuf: PChar;          // start env var entry in block
  // String list for new environment vars
  EnvVars := TStringList.Create;
    // include current block if required
    if IncludeCurrent then
    // store given environment vars in list
    if Assigned(NewEnv) then
    // Calculate size of new environment block
    Result := 0;
    for Idx := 0 to Pred(EnvVars.Count) do
      Inc(Result, Length(EnvVars[Idx]) + 1);
    // Create block if buffer large enough
    if (Buffer <> nil) and (BufSize >= Result) then
      // new environment blocks are always sorted
      EnvVars.Sorted := True;
      // do the copying
      PBuf := Buffer;
      for Idx := 0 to Pred(EnvVars.Count) do
        StrPCopy(PBuf, EnvVars[Idx]);
        Inc(PBuf, Length(EnvVars[Idx]) + 1);
      // terminate block with additional #0
      PBuf^ := #0;
Listing 6

The way we use this function is similar to the idiom used by many Windows API functions (such as GetEnvironmentVariable). We first call the function with a nil buffer to find the required buffer size, then call it again with a buffer of correct size to receive the data.

This routine can be used along with the Windows CreateProcess API function to spawn a new process with only one environment variable (FOO=Bar) as follows:

function ExecProg(const ProgName: string; EnvBlock: Pointer): Boolean;
  {Creates new process for given program passing any given environment block}
  SI: TStartupInfo;         // start up info
  PI: TProcessInformation;  // process info
  CreateFlags: DWORD;       // process creation flags
  SafeProgName: string;     // program name: safe for CreateProcessW
  // Make ProgName parameter safe for passing to CreateProcessW
  SafeProgName := ProgName;
  // Set up startup info record: all default values
  FillChar(SI, SizeOf(SI), 0);
  SI.cb := SizeOf(SI);
  // Set up creation flags: special flag required for unicode
  // environments, which is want when unicode support is enabled.
  // NOTE: we are assuming that the environment block is in Unicode
  // on Delphi 2009 or later. CreateProcessW does permits it to be
  // ANSI, but we don't support that
  CreateFlags := CREATE_UNICODE_ENVIRONMENT;  // passing a unicode env
  CreateFlags := 0;
  // Execute the program
  Result := CreateProcess(
    nil, PChar(SafeProgName), nil, nil, True,
	CreateFlags, EnvBlock, nil, SI, PI
Listing 7

Back to list

Demo Code

A demo program to accompany this article can be found in the delphidabbler/article-demos Git repository on GitHub.

You can view the code in the article-06 sub-directory. Alternatively download a zip file containing all the demos by going to the repository's landing page and clicking the Clone or download button and selecting Download ZIP.

The demo is described in the ReadMe.txt that is included with the source code.

This source code is merely a proof of concept and is intended only to illustrate this article. It is not designed for use in its current form in finished applications. The code is provided on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. The code is open source – see the source files for any licensing terms.

Going Further

My Environment Variables Unit provides a set of routines and a component that use the methods discussed here to access environment variables.