Monday, April 28, 2008

Folders kept in use

Some time ago I noticed that a couple of small (conversion) programs of mine showed some strange effect. Folders that were used were kept in use. If, even after closing down the program, I tried to delete the folders, Windows told me they were in use.

I looked high and low for this, but in the end found the cause of it all. I didn't close a Find in the folders. Putting a try..finally in the code did the trick. This guaranteed closing the Find, no matter what. So, if you experience that folders are kept in use, go look for this one.


procedure foo;
var
sr: TSearchRec;
ok: boolean;
begin
ok := (FindFirst('*.*', faAnyFile, sr)=0);
try
while ok do
begin
goDoSomething();
ok := (FindNext(sr)=0);
end;
finally
FindClose(sr);
end;
end;


Bye,
Bart

2 comments:

Fernando Madruga said...

Thanks for the tip! Can always come in handy!

Jolyon Smith said...

Ah yes, easily done with the Unholy "Find" Trinity.

I always used to forget whether the FindClose() had always to be performed or only if FindFirst() found something.

As an aside could I suggest the following improvements:

procedure foo;
var
sr: TSearchRec;
begin
try
if (FindFirst('*.*', faAnyFile, sr) = 0) then
repeat
goDoSomething();
until (FindNext(sr) <> 0);
finally
FindClose(sr);
end;
end;


Removes the need for the "ok" variable and simplifies the looping.

In this age where we are preoccupied with expressing intent we ironically often lose sight of the fact that we can oftentimes improve clarity of intent without having to resort to anonymous methods, lambda expressions, generics and other clever-clever tricks.

;)