Monday, May 7, 2018

Delete files in Delphi


http://wiki.freepascal.org/mysql


I checked the readonly property of the files. The directory d:\multifilter was write-protected (I could not change this) but all files in it could be manipulated ad libitum.
So I checked if with inclusion of
Code: Pascal  [Select]
  1. deletefile(d:\multifilter\b0.jpg);
at the beginning of the program b0.jpg was deleted, ok.

Also
Code: Pascal  [Select]
  1. files:='d:\multifilter\');
  2. deletefile(files+'b1.jpg');
worked.

Also
Code: Pascal  [Select]
  1.   files:='d:\multifilter\');
  2.   n:=2;
  3.   Str(n,nstring);
  4.   fbstring:=files+'b'+nstring+'.jpg';
  5.   deletefile(fbstring);
worked!

Also
Code: Pascal  [Select]
  1.   for n:=0 to nmax-1 do
  2.   begin
  3.   Str(n,nstring);
  4.   fbstring:=files+'b'+nstring+'.jpg';
  5.   deletefile(fbstring);
  6.   end;
worked!!!

But the deletefile() directly before the savefile() (as discussed before) later on in the program does not work. Very rare! (The savefile() alone did not overwrite the old files - this was the cause of the whole problem).
So, I put the deletes at the first possible place (when it is clear if and how many files have to be deleted). And it works!




-------------




Example code : Try to delete a file twice
var
  fileName : string;
  myFile   : TextFile;
  data     : string;

begin
  // Try to open a text file for writing to
  fileName := 'Test.txt';
  AssignFile(myFile, fileName);
  ReWrite(myFile);

  // Write to the file
  Write(myFile, 'Hello World');

  // Close the file
  CloseFile(myFile);

  // Reopen the file in read mode
  Reset(myFile);

  // Display the file contents
  while not Eof(myFile) do
  begin
    ReadLn(myFile, data);
    ShowMessage(data);
  end;

  // Close the file for the last time
  CloseFile(myFile);

  // Now delete the file
  if deletefile(fileName)
  then ShowMessage(fileName+' deleted OK')
  else ShowMessage(fileName+' not deleted');

  // Try to delete the file again
  if deletefile(fileName)
  then ShowMessage(fileName+' deleted OK again!')
  else ShowMessage(fileName+' not deleted, error = '+
                   IntToStr(GetLastError));
end;
Show full unit code
   Hello World
   Test.txt deleted OK
   Test.txt not deleted, error = 2

No comments:

Post a Comment

Коментар: