Mega Code Archive

 
Categories / Delphi / Functions
 

Deletefile - delete a file specified by its file name sysutils unit

function DeleteFile ( const FileName : string ) : Boolean; Description The DeleteFile function deletes a file given by its file name FileName. The file is looked for in the current directory. If the file was deleted OK, then True is returned, otherwise False is returned. This function is easier to use than the equivalent System unit Erase routine. Notes Warning : the Windows unit also has a DeleteFile function that takes a PChar argument. To ensure that you use are using the intended one, type SysUtils.DeleteFile. Related commands AssignFile Assigns a file handle to a binary or text file CloseFile Closes an open file Erase Erase a file Rename Rename a file RenameFile Rename a file or directory 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