Sunday, November 8, 2009

Retrieve special folders using static class

There are many times when you need the path to System32 or Windows folder or event the drive where windows is installed, at this time you need to get those paths dynamically because not everyone installs windows on default drive C:.
I've created a class specially for that reason without using the shell functions
unit uDGSysFolders;

interface

uses
    SysUtils,
    Windows;

(* define a TBuffer type as array of char *)
type TBuffer = array[0..250] of Char;

(* store it's size in a constant for faster access *)
const szBuffer = sizeof(TBuffer);

(* declare a static(doesn't need creation) class *)
type DGSystemFolders = class
     public
           (* C:\Windows\System32 *)
           class function System32Folder: string;
           (* C:\Windows *)
           class function WindowsFolder: string;
           (* C:\ *)
           class function WindowsDrive: string;
           (* C *)
           class function WindowsDriveChar: Char;
     end;

implementation

{ DGSystemFolders }

class function DGSystemFolders.System32Folder: string;
var Buffer : TBuffer;
begin
     GetSystemDirectory(Buffer, szBuffer);
     Result := Buffer;
end;

class function DGSystemFolders.WindowsDrive: string;
var tmp : string;
begin
     tmp := System32Folder;
     Result := Copy(tmp, 1, Pos('\', tmp));
end;

class function DGSystemFolders.WindowsDriveChar: Char;
var tmp : string;
begin
     tmp := System32Folder;
     Result := tmp[1];
end;

class function DGSystemFolders.WindowsFolder: string;
var tmp : string;
    i : integer;
begin
     tmp := System32Folder;
     for i := Length(tmp) downto 1 do
         if tmp[i] = '\' then begin
            Result := Copy(tmp, 1, i -1);
            Exit;
         end;// if tmp[i] = '\' then begin
end;

end.
Usage: add uDGSysFolders to uses clause
...
begin
     ShowMessage(DGSystemFolders.System32Folder);
end;

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)