Mega Code Archive

 
Categories / Delphi / Files
 

A Quick Way to Determine If a File has One of Several File Extensions

Title: A Quick Way to Determine If a File has One of Several File Extensions Question: What is an easy way to determine if a file has one of several file extensions? Answer: You can quickly determine if a file has one of a number of file extensions with the use of the Pos() and ExtractFileExt() functions. The trick is to use the periods (.) to separate extention names which are containted in a string. For example: if (Pos(ExtractFileExt(sr.Name),'..lnk.exe') 1) then { do something } This is particularly helpful if you are scanning through a directory for a list of certain types of files. The following code populates a listbox with all the graphic files of which are bmps or jpegs from the Windows directory: procedure TForm1.Button1Click(Sender: TObject); var sr:TSearchRec; begin if (FindFirst('C:\Windows\*',faAnyFile,sr) = 0) then try repeat if (Pos(ExtractFileExt(sr.Name),'..bmp.jpg.jpeg') 1) then ListBox1.Items.Add(sr.Name); until (FindNext(sr) 0); finally FindClose(sr); end; end; Be sure to use the double period trick at the beginning of your string of extensions. This will prevent the directory (.) and previous directory (..) from being thought of as one of the files you would like to add.