Free Information Technology Magazines and eBooks

Monday, June 15, 2009

How to search for Files by extension name using LINQ

Previously on the blog post entitled How to read multiple files in a directory using LINQ, I discussed how easy to query files from a specified directory. On this topic, I will try to do the same task and much more. I will also show you how to implement IEnumerable Interface to handle the search results and reuse existing LINQ query to filter the result by extension name. Sample projects for both C# and VB.NET are available for download at the end of this article.


Here are the tasks we want to achieve on this .NET project.

1. The program should ask the user for a specific directory.
2. It will query the specified directory then display the number of files found.
3. The program should ask the user for filename extension to browse.
4. It will display the list of filenames equal to the extension the user entered.
5. The program should display the latest/newest file from the list.


To start building our project, follow these steps.

1. Create a New Console VB or C# Project.
2. Add the following required namespaces.

In VB

Imports System.Collections.Generic
Imports System.IO
Imports System.Linq


In C#

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


3. Then add the following sourcecode on your Main sub. (Take note of the additional GetAllFiles function. It should be added below the Main sub)

In VB

Module Module1

Sub Main()

Try
Console.WriteLine("Enter the directory you want to read.")
Dim lDir As String = ""
lDir = Console.ReadLine()

Dim fileList = GetAllFiles(lDir)

Console.WriteLine("{0} file(s) found on {1}", fileList.Count, lDir)

Console.WriteLine("Enter the file extension you want to browse. Format is .txt, .xml")
Dim lExt As String = "*.*"
lExt = Console.ReadLine()

' run a query for by extension using LINQ
' list all files order by filename
Dim Query1 = From file In fileList _
Where file.Extension.ToLower() = lExt.ToLower() _
Order By file.Name _
Select file

For Each file In Query1
Console.WriteLine(file.FullName)
Next


' Now sort the existing Query1 by creation time
Dim Query2 = From file In Query1 _
Order By file.CreationTime _
Select file.Name, file.CreationTime

' Get the latest/newest file
Dim latestFile = Query2.Last

Console.WriteLine("\r\nThe latest file is {0} in the {1}. Creation time: {2}", _
latestFile.Name, lDir, latestFile.CreationTime)

' Keep the console window open in debug mode
Console.WriteLine("Press any key to exit.")
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.ReadKey()
End Try


End Sub

' retrieve all files on the specified directory
Function GetAllFiles(ByVal root As String) As IEnumerable(Of FileInfo)
Return From file In My.Computer.FileSystem.GetFiles _
(root, FileIO.SearchOption.SearchAllSubDirectories, "*.*") _
Select New FileInfo(file)
End Function

End Module


In C#

static void Main()
{
try
{
Console.WriteLine("Enter the directory you want to read.");
string lDir = "";
lDir = Console.ReadLine();
string rootDir = @lDir;

IEnumerable<System.IO.FileInfo> fileList = GetAllFiles(rootDir);
Console.WriteLine("{0} file(s) found on {1}", fileList.Count(), lDir);

Console.WriteLine("Enter the file extension you want to browse. Format is .txt, .xml");
string lExt = "*.*";
lExt = Console.ReadLine();

//run a query for by extension using LINQ
//list all files order by filename
IEnumerable<System.IO.FileInfo> fileQuery =
from file in fileList
where file.Extension.ToLower() == lExt.ToLower()
orderby file.Name
select file;

foreach (FileInfo fi in fileQuery)
{
Console.WriteLine(fi.FullName);
}

// Get the latest/newest file
var latestFile =
(from file in fileQuery
orderby file.CreationTime
select new { file.FullName, file.CreationTime })
.Last();

Console.WriteLine("\r\nThe latest file is {0}. Creation time: {1}",
latestFile.FullName, latestFile.CreationTime);

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}

// retrieve all files on the specified directory
static IEnumerable<System.IO.FileInfo> GetAllFiles(string path)
{
if (!System.IO.Directory.Exists(path))
throw new System.IO.DirectoryNotFoundException();

string[] fileNames = null;
List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();

fileNames = System.IO.Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string name in fileNames)
{
files.Add(new System.IO.FileInfo(name));
}
return files;
}


You can also download the complete Visual Studio 2008 project on the following links:
VB.NET Sample Project
C# Sample Project

For more coding tips & tricks, subscribe now.

0 comments: