Friday, April 9, 2010

Fetch Files with more than one extension from a Directory and Sorth them

Hi All,
There may be requirements in your project sometimes where you may fetch files of Particular extensions from a directory.
The Simple way for extension say " .docx " , the Directory search pattern works.

string[] fns = Directory.GetFiles(@"D:\Documents\", "*.docx*");

However if you want to search files of more than one type(extension), here is the way.

CODE:

var sort = from fn in fns

where fn.Contains(".jpg") || fn.Contains(".txt") || fn.Contains(".png")

orderby new FileInfo(fn).CreationTime descending

select fn;


I hope you know var keyword :p.(The anonymous types introduced in C# 3.0).

In the above example it gives the collection.

So at the end you get filtered all files from the directory/folder by just providing the extension name in file.contains() syntax like fn.Contains(".jpg")

Also note that the files can also be sorted(ascending/descending) by file Size,lastAccess,LastWrite,CreationTime.
In above example the files are sorted by CreationTime.

Thanks,
Nitin Sharma
Happy Coding