Search code examples
delphiexportfilepathdesktop

How to create a folder on desktop?


I'm currently overhauling my dirt oval racing pointkeeping app a bit and I've decided to start with the folder saving aspect of my app.

I want to change the file path from just C:\ to a path that saves directly to the user's desktop to make saving and finding the saved folder from my application a lot easier (the user then writes selected CSV files to that folder).

Current code I'm using:

procedure TfrmExDialog.FormShow(Sender: TObject);
var
  sInput:string;
begin
  sInput:=InputBox('Folder creation','Please enter the name of event without spaces (instead of spaces you can use _ )','C:\');
  folderForToday:=sInput;
  createdir(folderForToday);
end;

Thanks in advance for the help!

Kind Regards
PrimeBeat


Solution

  • The desktop is just a folder like any other. You can find his path like this:

    var
        Path   : array [0..MAX_PATH] of Char;
        sInput : String;
    begin
        sInput := InputBox('Folder creation','Please enter the name of event without spaces (instead of spaces you can use _ )','C:\');
        sInput := sInput.Replace(' ', '_'); // Prevent spaces
        SHGetFolderPath(0, CSIDL_DESKTOP, 0, SHGFP_TYPE_CURRENT, @Path[0]);
        folderForToday := IncludeTrailingPathDelimiter(Path) + sInput;
        CreateDir(folderForToday);
    end;
    

    You can also use CSIDL_COMMON_DESKTOPDIRECTORY to get the desktop directory for all users. Look at Microsoft Documentation for all possible values.

    Add WinApi.ShlObj in the uses clause.

    Once you have the desktop folder, you can create your file there or create a sub folder for your files using the standard Delphi functions for the purpose.