« PreviousNext »

HowTo Filter System.IO.Directory.GetFiles with Linq

30 May 2008

Here we are going to see an easy way to enumerate files in a directory, filter the files with Linq, then bind the results to a ASP.NET repeater control. We will show you the old .NET 1x way of doing this, then the new and improved Linq way of doing this.

I had a method that would return a DataTable as results, then bind it to a ASP.NET Repeater control to display the file list of Exception Reports.

Old .NET 1.1 way of filtering a GetFiles list and returning as a bindable object

DataTable dtFiles = new DataTable();

dtFiles.Columns.Add("FullName", typeof(string));

dtFiles.Columns.Add("FileName", typeof(string));

 

foreach (string file in Directory.GetFiles(Server.MapPath("~/App_Data")))

{

    if (!file.Contains("ErrorReport"))

        continue;

    DataRow row = dtFiles.NewRow();

    row["FullName"] = file;

    row["FileName"] = System.IO.Path.GetFileName(file);

    dtFiles.Rows.Add(row);

}

 

this.repeaterFiles.DataSource = dtFiles;

this.repeaterFiles.DataBind();

 

Here is how to filter your GetFiles results with Linq

var fileList = from file in Directory.GetFiles(Server.MapPath("~/App_Data"))

               where file.Contains("ErrorReport")

               select new

               {

                   FullName = file,

                   FileName = System.IO.Path.GetFileName(file)

               };

this.repeaterFiles.DataSource = dtFiles;

this.repeaterFiles.DataBind();

You can see this is much cleaner, no need to create a DataTable with the results. By using the "select new" you are basically creating a collection with two properties (FullName, FileName) on the fly.

I found Pro LINQ to be an excellent read on the Linq subject.

Posted in .NET Programming, ASP.NET, Web | Trackback | del.icio.us | Top Of Page

No comments yet

Leave a Reply


You must be logged in to post a comment.