|
Buscando archivos recursivamente en el disco duro
Copyright © 2000 Ernesto
De Spirito
FindFile
Esta función que mostramos abajo recibe como parámetros una especificación
de archivos (como por ejemplo 'C:\Mis Documentos\*.xls' o 'C:\*' si quiere
buscar todos los archivos del disco duro) y opcionalmente un conjunto de
atributos (exactamente como la función FindFirst de Delphi), y devuelve
una StringList con los nombres y caminos completos de los
ficheros encontrados. Debería liberar la StringList después de
usarla.
He aquí el código fuente:
interface
uses SysUtils, Classes;
function FindFile(const filespec: TFileName; attributes: integer
= faReadOnly Or faHidden Or faSysFile Or faArchive): TStringList;
implementation
function FindFile(const filespec: TFileName;
attributes: integer): TStringList;
var
spec: string;
list: TStringList;
procedure RFindFile(const folder: TFileName);
var
SearchRec: TSearchRec;
begin
// Busca todos los archivos concordantes
// en la carpeta actual y agrega sus nombres
// a la lista
if FindFirst(folder + spec, attributes,
SearchRec) = 0 then begin
try
repeat
if (SearchRec.Attr and faDirectory = 0)
or (SearchRec.Name <> '.')
and (SearchRec.Name <> '..') then
list.Add(folder + SearchRec.Name);
until FindNext(SearchRec) <> 0;
except
FindClose(SearchRec);
raise;
end;
FindClose(SearchRec);
end;
// Ahora busca en las subcarpetas
if FindFirst(folder + '*', attributes
Or faDirectory, SearchRec) = 0 then begin
try
repeat
if ((SearchRec.Attr and faDirectory) <> 0) and
(SearchRec.Name <> '.') and(SearchRec.Name <> '..') then
RFindFile(folder + SearchRec.Name + '\');
until FindNext(SearchRec) <> 0;
except
FindClose(SearchRec);
raise;
end;
FindClose(SearchRec);
end;
end; // procedure RFindFile dentro de FindFile
begin // function FindFile
list := TStringList.Create;
try
spec := ExtractFileName(filespec);
RFindFile(ExtractFilePath(filespec));
Result := list;
except
list.Free;
raise;
end;
end;
Llamada de ejemplo
Puede probar esta función colocando un cuadro de lista (TListBox)
y un botón en un formulario y agregando el siguiente código en el
evento OnClick del botón:
procedure TForm1.Button1Click(Sender: TObject);
var
lista: TStringList;
begin
lista := FindFile('C:\Delphi\*.pas');
ListBox1.Items.Assign(lista);
lista.Free;
end;
|