Title: Programmatically Detect the MyDocuments Folder for the Current Windows User using Delphi
The "MyDocuments" folder in Windows should be used to store user created documents such as text documents or presentations.
If your Delphi program creates application specific documents you want to be stored in the "MyDocuments" folder for the currently logged Windows user, you need to programmatically determine the path to the "MyDocuments" folder.
Here's a custom function GetMyDocuments which returns the full path to the MyDocuments folder for the current Windows user:
uses shlobj, ...
function GetMyDocuments: string;
var
r: Bool;
path: array[0..Max_Path] of Char;
begin
r := ShGetSpecialFolderPath(0, path, CSIDL_Personal, False) ;
if not r then raise Exception.Create('Could not find MyDocuments folder location.') ;
Result := Path;
end;
procedure TMyForm.FormCreate(Sender: TObject) ;
var
myDocFolder : string;
begin
myDocFolder := GetMyDocuments;
ShowMessage(Format('MyDocuments folder for the current user: "%s"',[myDocFolder])) ;
end;
Note 1: The function that does the trick is "ShGetSpecialFolderPath". It is located in the "SHLOBJ" unit.
Note 2: Application specific data, like INI files should be placed in the "Application Data" folder.