Delphi Components Page
I’ve updated the Delphi components page, restructured it and added a whole bunch of new items. I’ll certainly be adding more to it later. You can check it out here.
Delphi: Remove Directory Recursively
If you ended up looking for this, then you probably came to the conclusion that Windows.RemoveDirectory() can not remove a directory that has files/directories in it.
About.com proposes the following solution: http://delphi.about.com/cs/adptips1999/a/bltip1199_2.htm
I can assure you that this solution is valid and works. However, the code as it is proposed there will move the deleted folder into the recycle bin which is something you will want to avoid more often than not. The following code I modified to remove that effect:
function RemoveDirectory(const Path: string): Boolean;
var
SHFileOpStruct: TSHFileOpStruct;
DirBuf: array[0..255] of Char;
begin
if DirectoryExists(Path) then
try
FillChar(SHFileOpStruct, Sizeof(SHFileOpStruct), 0);
FillChar(DirBuf, Sizeof(DirBuf), 0);
StrPCopy(DirBuf, Path);
with SHFileOpStruct do
begin
Wnd := 0;
pFrom := @DirBuf;
wFunc := FO_DELETE;
fFlags := FOF_NOCONFIRMATION or FOF_SILENT;
end;
Result := SHFileOperation(SHFileOpStruct) = 0;
except
Result := False;
end;
end;
Another way of doing this is recursing through all directories and removing all files before you remove the directories as seen here, but I imagine that might be slower as in the method above, the OS takes care of that internally:
function RemoveDirectory(const Path: string): Boolean;
var
sRec: TSearchRec;
t: string;
begin
if DirectoryExists(Path) then
try
t := IncludeTrailingPathDelimiter(Path);
if FindFirst(t + '*.*', faNormal or faDirectory, sRec) = 0 then
begin
repeat
if ((sRec.Attr and faDirectory) <> 0) and (sRec.Name <> '.') and
(sRec.Name <> '..') then
RemoveDirectory(t + sRec.Name)
else
DeleteFile(t + sRec.Name);
until FindNext(sRec) <> 0;
FindClose(sRec);
end;
Result := Windows.RemoveDirectory(PChar(t));
except
Result := False;
end;
end;
Delphi: Exposing Protected Properties
On occasion you’ll find yourself wanting to access a a protected property from a class in a different unit. If this is a 3rd party unit, you’ll often not want to modify it’s source code. So how do you access it? Sub-classing the class as you might have guessed, however, you can do this in very little code.
Delphi will allow any class to use protected properties from other classes as long as they are in the same unit. We can use this to our advantage. By creating a subclass, we can essentially use this to access protected values in the class we’re sub-classing, it works the same way, because your subclass is in the unit you need it in. All you have to do, is cast the object to the subclass and you’re set to access the protected property.
unit Example; interface uses Classes; type TStringListEx = class(TStringList); implementation function SLChanged(const SL: TStringList): Boolean; begin Result := TStringListEx(SL).Changed; end; end.



