Tuesday, November 12, 2013

Iterating files in a folder based on file extensions using LINQ

Using LINQ, iterating through specific files based on file extensions in a directory can be somewhat simplified.

using System.Linq;
using System.IO;

string fileExtensions = ".pdf, .tif, .jpg, .bmp";
string [] fileExtensionArray
    fileExtensions.split(',').Select(e => e.Trim().ToLower()).ToArray();

DirectoryInfo di = new DirectoryInfo("C:\\myDir");
FileInfo[] fileInfoArray = 
        .Where(f => fileExtensionArray.Contains(f.Extension.ToLower()))
foreach( var item in fileInfoArray )
    string fileFullPath = item.FullName;
    // Perform your work with the desired file here.

No comments: