How can i select a file in Delphi

16,785

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'
Share:
16,785
M.Gómez
Author by

M.Gómez

Gava student eager to learn from the best , and help where I can.

Updated on June 16, 2022

Comments

  • M.Gómez
    M.Gómez almost 2 years

    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.

  • whosrdaddy
    whosrdaddy over 8 years
    please use a try/finally clause when dealing with objects, as shown in the excellent answer from @fantaghirocco