Search code examples
windowsdelphi-7

how do I free memory of these .txt files


Working with TXT files I've been seeing a message lately "cannot create file ('c:\01.txt') the process cannot acess the file because it is being used by another process" how do I free memory of these .txt files?

I have this code by Mr. Nice and when i trying to change or add new using: ListBox1.Items.savetofile('01.txt');

"cannot create file ('c:\01.txt') the process cannot acess the file because it is being used by another process"

var
  path: string;
  SR: TSearchRec;
  tempFile: TextFile;
  line: string;
begin
  path:= 'C:\my all txt\';
  if FindFirst(path + '*.txt', faAnyFile, SR) = 0 then
  begin
    repeat
      if (SR.Attr <> faDirectory) then
      begin
        AssignFile(tempFile, path + SR.Name);
        Reset(tempFile);
        while not Eof(tempFile) do
        begin
          Readln(tempFile, line);
          ListBox1.Items.Add(line);
        end;
      end;
    until FindNext(SR) <> 0;
    FindClose(SR);
  end;
end;

Solution

  • You never close files after you're finished with them. You need to use CloseFile once you've reached Eof(tempfile):

    while not Eof(tempfile) do
    begin
      Readln(tempfile, line);
      ListBox1.Items.Add(line);
    end;
    CloseFile(tempfile);