Tuesday, October 30, 2007

Store User and Application Data in the Correct Location

SHGetFolderPath retrieves the full path of a known folder identified.

Here's a custom wrapper function around the SHGetFolderPath API to help you get any of the standard folders for all or the currently logged Windows user.

uses SHFolder;

function GetSpecialFolderPath(folder : integer) : string;
___ path: array [0..MAX_PATH] of char;
___if SUCCEEDED(SHGetFolderPath(0,folder,0,SHGFP_TYPE_CURRENT,@path[0])) then
______ Result := path
______Result := '';
Here's an example of using the SHGetFolderPath function:
  • Drop a TRadioButtonGroup (name: "RadioGroup1") on a form
  • Drop a TLabel (name: "Label1") on a form
  • Add 5 items to the radio group:
    1. "[Currenty User]\My Documents"
    2. "All Users\Application Data"
    3. "[User Specific]\Application Data"
    4. "Program Files"
    5. "All Users\Documents"
  • Handle the RadioGroup's OnClick event as:

Note: "[Current User]" is the name of the currently logged in Windows user.

//RadioGroup1 OnClick
procedure TForm1.RadioGroup1Click(Sender: TObject) ;
___index : integer;
___specialFolder : integer;
___if RadioGroup1.ItemIndex = -1 then Exit;

___index := RadioGroup1.ItemIndex;

___case index of
______//[Current User]\My Documents
______0: specialFolder := CSIDL_PERSONAL;
______//All Users\Application Data
______1: specialFolder := CSIDL_COMMON_APPDATA;
______//[User Specific]\Application Data
______2: specialFolder := CSIDL_LOCAL_APPDATA;
______//Program Files
______3: specialFolder := CSIDL_PROGRAM_FILES;
______//All Users\Documents
______4: specialFolder := CSIDL_COMMON_DOCUMENTS;

___Label1.Caption := GetSpecialFolderPath(specialFolder) ;
Note: The SHGetFolderPath is a superset of SHGetSpecialFolderPath.

You should not store application-specific data (such as temporary files, user preferences, application configuration files, and so on) in the My Documents folder. Instead, use an application-specific file that is located in a valid Application Data folder.

Always append a subfolder to the path that SHGetFolderPath returns. Use the following convention: "\Application Data\Company Name\Product Name\Product Version".

No comments: