LINQ to filesystem

Edit on GitHub

The past few hours, I've been experimenting with LINQ. As a sample application, I'm trying to create a small photo album website, which shows me all images in a specific folder on my webserver.

What does LINQ have to do with that? Everyone has used a loop over all files in a folder, and I decided to try LINQ for that matter. Here's how:


var rootFolder = "C:\\";
var selectedImages = from file in Directory.GetFiles(rootFolder, "*.jpg")
                             select new { Path = file,
                                          Name = new FileInfo(file).Name,
                                          CreationDate = new FileInfo(file).CreationTime,
                                          DirectoryName = new FileInfo(file).DirectoryName


There you go! A collection named "selectedImages", filled with anonymous class instances containg a file Path, Name, CreationDate and DirectoryName. This collection can now be bound to, for example, a GridView:


this.gridView1.DataSource = selectedImages;


EDIT: (mental note to myself: add LINQ keywords to syntax highlighter...) - done!

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment


2 responses

  1. Avatar for Jos
    Jos July 12th, 2008

    Could this code be extended to allow WHERE clauses (where name like '*.jpg' and ModifedDate > '1/1/2008'), or even aggregates (total filesize)? That would be even greater...

    Maybe it needs a dedicated Linq to FileSystem provider?


  2. Avatar for maartenba
    maartenba July 14th, 2008

    I've seen such a thing somewhere, but can't remember where...