Search code examples
delphidelphi-2010lazarus

Save values from Delphi to Disk: "Save" and "Save as"


I am creatinga program that saves some information (usually edit fields) on the disk using the following code:

  procedure TForm1.ToolButton3Click(Sender: TObject);   
    begin    
    if  Savedialog1.Execute then
         begin
            AssignFile(myFile, save.filename);
            ReWrite(myFile);
            customer.Name:=name.text;
            customer.LastName:= LastName.Text;
           //[...] <-- much more fields
            Write(myFile, customer);
            CloseFile(myFile);  
            end;

end;

And this code to open:

procedure TForm1.ToolButton12Click(Sender: TObject);
begin
  if opendlg.execute then begin
     Form1.Caption := 'Program Name '+' - '+extractfilename(Opendlg.FileName);

     if FileExists(opendlg.filename) then
    begin
     AssignFile(myfile, opendlg.filename);

    end;
    // Reopen the file in read only mode
   FileMode := fmOpenRead;
   Reset(myFile);

   // Display the file contents
   while not Eof(myFile) do
   begin
     Read(myFile, customer);

   Name.text:=customer.Name;
   LastName.Text:=customer.LastName; 
   //[...] <-- much more fields
end;
end;
end;   

I do not know if the method is the more accurate but it is what i'm using =(. So how can I make by clicking on the save button I just update the file that was previously saved without the need to reopen the save dialog? Thanks!


Solution

  • Like this:

    procedure TForm1.ToolButton3Click(Sender: TObject);   
    begin    
      if SaveDialog1.FileName = '' then
      begin
        if not SaveDialog1.Execute then
          Exit;
        end;
      end;
      AssignFile(myFile, SaveDialog1.FileName);
      ...
    end;