Mega Code Archive

 
Categories / Delphi / Files
 

Fileoperations on a whole tree

Title: Fileoperations on a whole tree Question: How to implement a general function that can be used by other function to manipulate the file system. Answer: The function GetAllFiles will be the base function to easily implement operations that apply to a whole directory tree. GetAllFiles retrieves in a stringlist all files that match the criteria. The clou is the recursive call of the function. procedure GetAllFiles(aPathPlusMask:string;aSubFolders: boolean; aResultList: TStringList); var Search: TSearchrec; hDir: string; hMask: string; begin hMask := aPathPlusMask; hDir := ExtractFilepath(aPathPlusMask); if hDir[length(hDir)]'\' then hDir := hDir + '\'; // Attention: FindFirst finds all files in the actual folder // if hDir is not valid if not DirectoryExists(hDir) then EXIT; if FindFirst(hMask, $23, Search)= 0 then repeat aResultList.Add(hDir + Search.Name); until FindNext(Search)0; if aSubFolders then if FindFirst(hDir + '*.*',fadirectory, Search)= 0 then repeat if((search.attr and fadirectory)=fadirectory) and (search.name[1]'.') then GetAllFiles(hDir+Search.Name+'\'+hMask, aSubFolders, aResultList); until FindNext(Search) 0; end; Now its easy to implement a function that sets all files attributes: procedure SetAllFilesAttr(aPathPlusMask: string; aSubFolders: boolean; aAttr: Integer); var i: integer; hStrList: TStringList; begin hStrList:= TStringList.Create; GetAllFiles(aPathPlusMask,aSubFolders, hStrList); for i := 0 to hStrlist.Count - 1 do FileSetAttr(hStrlist[i], aAttr); hStrList.Destroy; end; The call would look like this: SetAllFilesAttr('*.*', false, faArchive ); Functions like CopyAllFiles or FindInFiles can by realized the same way !