Wednesday, March 2, 2011

How to retrieve environment variables

Retrieving environment variables (such as PATH, COMSPEC, PROMPT, etc.) from 32bit programs is not so difficult since you can use the Win32 function "GetEnvironmentVariable()". On the other hand, if you're writing a 16bit program you have to do little bit more work. Following "GetEnvVar()" function can help you to easily retrieve environment variables regardless of whether your program is 16bit or 32bit:

 
const
{
 change the following value if you
 expect more than 250 char values
 from env. vars. set to 250 by
 default to be compatible with
 16bit versions of Delphi
}
  cnMaxVarValueSize = 250;


function GetEnvVar(
  const csVarName : string ) : string;
{$IFDEF WIN32}
var
  pc1,
  pc2  : PChar;
begin
{
 although you can use huge strings with
 Delphi 2.x, we'll use good old PChars
 and allocate memory here
}
  pc1 :=
    StrAlloc( Length( csVarName )+1 );
  pc2 :=
    StrAlloc( cnMaxVarValueSize + 1 );
  StrPCopy( pc1, csVarName );
  GetEnvironmentVariableA(
    pc1, pc2, cnMaxVarValueSize );
  Result := StrPas( pc2 );
  StrDispose( pc1 );
  StrDispose( pc2 );
end;

{$ELSE}

var
  w1  : Word;
  pc1 : PChar;
begin
  GetEnvVar     := '';

  w1 := Length( csVarName );

{$IFDEF Windows}
  pc1 := GetDosEnvironment;
{$ELSE}
  pc1 :=
    Ptr(Word( Ptr( PrefixSeg, $2C )^),
    0 );
{$ENDIF}
  while( #0 <> pc1^ ) do
  begin
    if( 0 = StrLIComp( pc1,
            @csVarName[ 1 ], w1 ) )
        and ( '=' = pc1[ w1 ] ) then
    begin
      GetEnvVar :=
        StrPas( pc1 + w1 + 1 );
      Exit;
    end;
    Inc( pc1, StrLen( pc1 ) + 1 );
  end;
  GetEnvVar := '';
end;
{$ENDIF}
Listing #1 : Delphi code. Download getenv (0.73 KB).
 
Now you can retrieve the environment variable PATH (for example) by using the following call:
 
GetEnvVar( 'PATH' );
Listing #2 : Delphi code. Download demo (0.14 KB).
 
Don't forget to add Windows and SysUtils units to your uses statement when using the above function.

Source : http://www.chami.com/tips/delphi/010997D.html

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Kang Iwan K-sev | Thank's for your visit To My Site - Ridwan Mulyana | Cibeureum