Thursday, April 9, 2009

Retrieve Shell Folders Using SHFolder

Windows has some special folders like My Documents, SendTo, Desktop or Favorites. The location of this folders are keep in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders

However, it is not encourage to retrieve the location of special folders using registry. The recommended way to retrieve is via windows API function SHGetFolderPath:

uses SHFolder;

var sDir: string;
begin
SetLength(sDir, MAX_PATH);
ZeroMemory(@sDir[1], MAX_PATH);
if Succeeded(SHGetFolderPath(0, CSIDL_PERSONAL, 0, 0, PAnsiChar(sDir))) then
ShowMessage(sDir);
end;

2 comments:

Anonymous said...

It did not work for me, PWideChar(sDir) instead of PAnsiChar(sDir) compiled.

I feel myself in the stone age in Delphi 2009 after Delphi 7, I have went from D4 to D6 to D7 but never ever seen so much break in every simple supporting library.

Anonymous said...

Uh oh, it emits an uncontrollable array filled with the special folder path and then #0s, so I can't concatenate the file name. Trim() does not help me.

changing
var sDir: string -> var sDir: array[0..MAX_PATH] of WideChar;
and PAnsiChar(sDir) of the original code to simply sDir in the SHGetFolderPath function not only compiles, but emits a concatenateable path :) Could you clean this up for me? Am I missing a project-wide setting?