Click here to Skip to main content
15,745,178 members
Please Sign up or sign in to vote.
4.33/5 (3 votes)
See more:
how can i get all files of a given directory as fileinfo[]?
i want to exclude more than 1 given extensions like(*.txt,*.doc)

Try this for fancy looks :

System.IO.FileInfo[] fi = new System.IO.DirectoryInfo(path).GetFiles().
       Where(f => !(f.FullName.EndsWith(".mp3") || f.Name.EndsWith(".txt"))).ToArray();

or if you want to get involved with regex
System.IO.FileInfo[] fi = new System.IO.DirectoryInfo(path).GetFiles().
       Where(s => !System.Text.RegularExpressions.Regex.IsMatch(s.Name, @"\.(txt|mp3|png)$")).ToArray();

Credits to OriginalGriff
Share this answer
RAJI @Codeproject 2-May-11 1:01am    
this worked great!!!!! thankssss!!!!!!
Easy way is to use Linq:
FileInfo[] files = new DirectoryInfo(path).GetFiles();
FileInfo[] excluded = (from f in files
                       where f.Extension != ".txt" && f.Extension != ".jpg"
                       select f).ToArray();
foreach (FileInfo file in excluded)
Share this answer
Ankit Rajput 30-Apr-11 7:38am    
Nice Answer. My 5
Kim Togo 30-Apr-11 7:42am    
My 5. The power of LINQ.
I think, if you really what to speedup things. Then change ".GetFiles()" to ".EnumerateFiles()".
You can start enumerating the collection of FileInfo objects before the whole collection is returned. Where ".GetFiles()" you must wait for the whole array of FileInfo objects to be returned before you can access the array.
I think bellow code will help you.
DirectoryInfo dir = new DirectoryInfo("directoryAddress");
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
  // Do your Coding here
Share this answer
Ankit Rajput 30-Apr-11 7:39am    
Downvoted. Answer is not sufficient for the question
I suspect you can't do this in one step using .NET stuff (but am willing to be proved wrong)!

Probably need to use Directory.GetFiles to get all files - iterate over that and eliminate files with extensions you don't want / get the FileInfo for those you do and add to a List<fileinfo> - then use that to generate a FileInfo[] array.
Share this answer
OriginalGriff 30-Apr-11 7:37am    
Consider yourself proved wrong! :laugh:
Linq can do it with ease...
NuttingCDEF 30-Apr-11 7:49am    
More than happy to learn new tricks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900