Using platform-specific paths in Delphi

The TPath class from System.IOUtils unit give you the ability to access system and application specific paths and folders, like the user folders (My documents, My music, My pictures, …).

With this class, you can handle access to those paths in all supported platfroms (Windows, Linux, MacOS, iOS and Android). You don’t have to worry about how to write the path’s string for each platform.

As we know, these special paths can have a different behavior from platform to another : For example, some paths can be accessed by the file browser on a platform while they are inaccessible to the user on other platforms. This difference can affect your strategy if you want to deploy some hidden files or assets with your app in the distribution package.

On Android, assets must be placed in the Document or the Shared document folder because they are the only accessible folders for the app installer, but on Windows, you are free to use many of the protected and hidden folders (like the Cache, Temp or the current app folder) to hide your assets during app setup.

The difference is, on Android, Documents folder’s content is hidden to the file browser, while this folder’s content is visible to the user.

So, to retrieve your assets on runtime, you can use a custom function to get the required paths differently on each platform.

Let’s say you want to access a file in the Document folder on Android, while it is located in the your app folder on Windows. Then you can wrote a custom function like the following :

function GetMyAssets(var AssetName : string) : string;
begin
{$IF Defined(ANDROID)} 
Result := TPath.Combine(TPath.GetDocumentsPath, AssetName);

{$ELSEIF Defined(MSWINDOWS)}
Result := TPath.Combine(TPath.GetLibraryPath, AssetName);

{$ENDIF}
end;

Don’t forget to add this unit to the uses :

uses
..., System.IOUtils, ...

How to call this function ?

For example, you need this function to access a file which store your dataset content. Just load your file using this call :

MyDataSet.LoadFromFile(GetMyAssets('data01.json'));

See also

Leave a Reply