Reputation: 1838
procedure TForm1.Button1Click(Sender: TObject);
begin
if not deletefile('c:\test') then
raiselastoserror
end;
i get os error 5 : access denied when i use the same code to delete a file say wwj.txt it works fine but doesnt work for folders what am i doing wrong?
Upvotes: 2
Views: 3208
Reputation: 163247
What you're doing wrong is using DeleteFile
to delete something that isn't a file. The documentation advises you:
- To recursively delete the files in a directory, use the
SHFileOperation
function.- To remove an empty directory, use the
RemoveDirectory
function.
The documentation doesn't explicitly tell you not to use DeleteFile
on directories, but it's implied by those other two instructions.
Upvotes: 2
Reputation: 6747
Use the RemoveDir() procedure instead. Make sure it is not a current directory for your app, or any other too, or it will remain. SysUtils must be used to get the function.
If you need to, delete the contents of the directory first (below). Recursive deleting is possible, and consider the implications of the '.' test if you use directories or files with '.'.
procedure DeleteFiles( szDBDirectory : string );
var
szFile : string;
SearchRec: TSearchRec;
szSearchPath : string;
nResult : integer;
begin
szSearchPath := szDBDirectory;
nResult := FindFirst(szSearchPath + '\*.*', faAnyFile, SearchRec);
try
while 0 = nResult do
begin
if('.' <> SearchRec.Name[1]) then
begin
szFile := szSearchPath + '\' + SearchRec.Name;
{$IFDEF DEBUG_DELETE}
CodeSite.Send('Deleting "' + szFile + '"');
{$ENDIF}
FileSetAttr(szFile, 0);
DeleteFile(szFile);
end;
nResult := FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
end;
Upvotes: 5
Reputation: 33222
You can use the function SHFileOperation from the Windows API. A reference to it is defined in ShellApi. However, I would recommend looking into the Jedi Code Library. The unit JclFileUtils contains a DeleteDirectory function which is much easier to use; it even has the option to send the deleted directory to the recycle bin.
Upvotes: 3
Reputation: 13163
You can use the shell functions. According to delphi.about.com, this will delete nonempty folders even if they contain subfolders:
uses ShellAPI;
Function DelTree(DirName : string): Boolean;
var
SHFileOpStruct : TSHFileOpStruct;
DirBuf : array [0..255] of char;
begin
try
Fillchar(SHFileOpStruct,Sizeof(SHFileOpStruct),0) ;
FillChar(DirBuf, Sizeof(DirBuf), 0 ) ;
StrPCopy(DirBuf, DirName) ;
with SHFileOpStruct do begin
Wnd := 0;
pFrom := @DirBuf;
wFunc := FO_DELETE;
fFlags := FOF_ALLOWUNDO;
fFlags := fFlags or FOF_NOCONFIRMATION;
fFlags := fFlags or FOF_SILENT;
end;
Result := (SHFileOperation(SHFileOpStruct) = 0) ;
except
Result := False;
end;
end;
Upvotes: 3