Search code examples
delphivcl

How can i select a file in Delphi


I need to make 'Graphic User Interface' and I need some VCL component to select some file.

This component have to select the file, but the user don't have to put the name of the file.

I am searching information but nothing helps me.


Solution

  • Vcl.Dialogs.TOpenDialog can be used for this purpose.

    See also UsingDialogs.

    procedure TForm1.Button1Click(Sender: TObject);
    var
      selectedFile: string;
      dlg: TOpenDialog;
    begin
      selectedFile := '';
      dlg := TOpenDialog.Create(nil);
      try
        dlg.InitialDir := 'C:\';
        dlg.Filter := 'All files (*.*)|*.*';
        if dlg.Execute(Handle) then
          selectedFile := dlg.FileName;
      finally
        dlg.Free;
      end;
    
      if selectedFile <> '' then
        <your code here to handle the selected file>
    end;
    

    Notice that the example here assumes that a TButton named Button1 is dropped to the form and the TForm1.Button1Click(Sender: TObject) procedure is assigned to the button OnClick event.


    Multiple file extensions can be used in the TOpenDialog.Filter property by concatenating them together using the | (pipe) character like this:

    'AutoCAD drawing|*.dwg|Drawing Exchange Format|*.dxf'