Get the path of 'Program Files'  

Send By: Ferran Piņana
Web : N.A.
Email: ferran77@haley.es
Date: 07/05/00

Tip accessed 495 times

 




As I had not sent anything for a long time, here I send you a code piece that has cost me a lot to obtain.
In the work, I have made an installer for applications based on Delphi, BDE and Interbase, and for it, I have needed to know it the localization of the system directories.
In the case of WINDOWS and WINDOWS\SYSTEM, this is easy, some very kind APIs that serve to such an effect exist.
The problem went when trying to locate 'Program Files'. If, there is a key in the registry, but in Windows NT, that key contains an environment variable.
So after many fail intents, I found the way to make work the same procedure in Windows 9x, Windows NT 4 and Windows 2000.
It is tested in the three environments and it always works.

Ferran.


 Uses Registry;

 Var
   rDI_WinSys,rDI_Win,rDI_ProgFiles:String;

 Function ResolveEnvVars(Const S:String):String;
 Var
   F:Word;
   IsASysVar:Boolean;
   SysVar:String;
   buffer:pchar;
 Begin
   IsASysVar:=False;
   For F:=1 To Length(S) Do
   Begin
     If IsASysVar Then
     Begin
       If S[F]='%' Then
       Begin
         GetMem(buffer,200);
         GetEnvironmentVariable(PChar(SysVar),PChar(buffer),200);
         Result:=Result+buffer;
         FreeMem(buffer,200);
         IsASysVar:=False;
       End
       Else
         SysVar:=SysVar+S[F];
     End
     Else
     Begin
       If S[F]='%' Then
       Begin
         SysVar:='';
         IsASysVar:=True;
       End
       Else
         Result:=Result+S[F]
     End;
   End;
 End;

 Procedure GetSystemDirs;
 Var
   pcData:PChar;
   pcDataSize:Cardinal;
   Reg:TRegistry;
 Begin
   //Obtener el directorio "Windows\System\"
   pcDataSize:=0;
   pcData:=Nil;
   pcDataSize:=GetSystemDirectory(pcData,pcDataSize);
   pcData:=AllocMem(pcDataSize+1);
   GetSystemDirectory(pcData,pcDataSize);
   rDI_WinSys:=pcData;
   FreeMem(pcData);

   //Obtener el directorio "Windows\"
   pcDataSize:=0;
   pcData:=Nil;
   pcDataSize:=GetWindowsDirectory(pcData,pcDataSize);
   pcData:=AllocMem(pcDataSize+1);
   GetWindowsDirectory(pcData,pcDataSize);
   rDI_Win:=pcData;
   FreeMem(pcData);

   //Obtener el directorio "Archivos de Programa\"
   Reg:=TRegistry.Create;
   Reg.RootKey:=HKEY_LOCAL_MACHINE;
   If Not Reg.OpenKeyReadOnly('\SOFTWARE\Microsoft\Windows\CurrentVersion') Then
     Raise Exception.Create('Program Files Path Error');
   rDI_PROGFILES:=ResolveEnvVars(Reg.ReadString('ProgramFilesPath'));
 End;

 procedure TForm1.Button1Click(Sender: TObject);
 begin
   GetSystemDirs;
   memo1.Lines.Add(rDI_WinSys);
   memo1.Lines.Add(rDI_Win);
   memo1.Lines.Add(rDI_ProgFiles);
 end;