|
Getting Windows important directories
Copyright © 2000 Ernesto
De Spirito
Overview
Many people think the Windows directory is C:\WINDOWS, that the
System directory is C:\WINDOWS\SYSTEM, the temporary directory
is C:\WINDOWS\TEMP and the program files directory
is C:\PROGRAM FILES. Well, the fact is that this is not always true.
For example, the temporary directory is usually determined by environment
variables, and in Spanish installations the default program files directory
is C:\ARCHIVOS DE PROGRAMA.
Here we present a set of functions to get the actual location of these
important directories. These functions need
the Windows and SysUtils units.
They all raise an exception if they fail.
The Windows Directory
function GetWindowsDir: TFileName;
var
WinDir: array [0..MAX_PATH-1] of char;
begin
SetString(Result, WinDir, GetWindowsDirectory(WinDir, MAX_PATH));
if Result = '' then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
The Windows System Directory
function GetSystemDir: TFileName;
var
SysDir: array [0..MAX_PATH-1] of char;
begin
SetString(Result, SysDir, GetSystemDirectory(SysDir, MAX_PATH));
if Result = '' then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
The Program Files Directory
function GetProgramFilesDir: TFileName;
begin
Result := GetRegistryData(HKEY_LOCAL_MACHINE,
'\Software\Microsoft\Windows\CurrentVersion',
'ProgramFilesDir'); // or 'ProgramFilesPath'
end;
The Temporary Directory
This is the directory where applications can store temporary files. You
should not use for this purpose the directory where your application is
located for two reasons: 1) Using a common temporary directory simplifies
the cleaning process when users want to recover unused hard disk space,
and 2) In Windows NT the user (and thus your application) might not have
enough permissions to create files in the directory where it is installed.
The following function returns the location of the temporary directory and
attempts to create it if it doesn't exist.
function GetTempDir: TFileName;
var
TmpDir: array [0..MAX_PATH-1] of char;
begin
try
SetString(Result, TmpDir, GetTempPath(MAX_PATH, TmpDir));
if not DirectoryExists(Result) then
if not CreateDirectory(PChar(Result), nil) then begin
Result := IncludeTrailingBackslash(GetWindowsDir) + 'TEMP';
if not DirectoryExists(Result) then
if not CreateDirectory(Pointer(Result), nil) then begin
Result := ExtractFileDrive(Result) + '\TEMP';
if not DirectoryExists(Result) then
if not CreateDirectory(Pointer(Result), nil) then begin
Result := ExtractFileDrive(Result) + '\TMP';
if not DirectoryExists(Result) then
if not CreateDirectory(Pointer(Result), nil) then begin
raise Exception.Create(SysErrorMessage(GetLastError));
end;
end;
end;
end;
except
Result := '';
raise;
end;
end;
|