0

In my program I have an openfiledialogue and a savefiledialogue. Whenever I press cancel in these dialogue I get an I/O error 6. How do I remove this error?

procedure TForm1.Open1Click(Sender: TObject);
var
  s: string;

  // Declares a file type for storing lines of text
  t: TextFile;
begin
  mmo1.Lines.Clear;

  // Set up the starting directory to be the current one
  dlgOpen1.InitialDir := 'Libraries\Documents';

  // Opens the file Dialogue
  dlgOpen1.Execute;

  // Assigns contents of the chosen
  AssignFile(t, dlgOpen1.FileName);

  // Opens a file given by FileHandle for read, write or read and write access
  // Must use AssignFile to assign a file to the FileHandle before using Reset
  Reset(t);

  // The While keyword starts a control loop that is executed as long as the
  // - Expression is satisfied (returns True)
  // The Eof function returns true if the file given by FileHandle is at the end
  // All this essentialy adds the contents of the text file, line by line until
  // - there is no more text to be added
  while not Eof(t) do
  begin

    // Reads a complete line of data from a text file
    Readln(t, s);

    mmo1.Lines.Add(s);
  end;
  CloseFile(t);

end;
  • 1
    Please show your code! – Delphi Coder Oct 18 '20 at 08:50
  • @DelphiCoder I put it in now – I_Suck_At_Programming04 Oct 18 '20 at 08:58
  • 1
    @I_Suck_At_Programming04: Did you try to run the program in the debugger? To do this, set a breakpoint on the first `begin` (either by clicking the ruler on this line, or by pressing F5 when the caret is on this line -- in both cases, this results in a red dot in the ruler). Then run the program (F9). When you reach this function, you are taken to the source code, and you can run it one line at a time by pressing F8 (or use F7 to enter a subroutine). The debugger is an invaluable tool. In this case, it would have shown you exactly what is wrong ("Oh, it continues even tg the user cancelled!"). – Andreas Rejbrand Oct 18 '20 at 10:22
  • @AndreasRejbrand Thank you for the tip. I'll do that next time – I_Suck_At_Programming04 Oct 19 '20 at 11:26

2 Answers2

3

You must do:

if dlgOpen1.Execute then
begin
    // ...all your file management here
end;

dlgOpen1.execute return false if user cancels dialog.

Diego Muñoz
  • 191
  • 1
  • 3
3

You have to check the return value of dlgOpen1.Execute:

if not dlgOpen1.Execute then
    Exit;
fpiette
  • 11,983
  • 1
  • 24
  • 46