Posted by: Cirilo Meggiolaro | 01/20/2009

Tip of the day #98 – Using LINQ queries with the System.IO classes

LINQ is really flexible and very easy to work with. You may use LINQ to perform several tasks and is handful especially with collections. We may use the queries in conjunction with existing classes such as System.IO classes to filter existing files in a directory by their sizes for example.

The following code snippet describes that task:

DirectoryInfo dir = new DirectoryInfo(@”C:\”);

/// Selects all files from a directory
/// that have size greater than 100kb.

var largeFiles = from fileName in dir.GetFiles()
                       where fileName.Length > 100000
                       select fileName;

if ((largeFiles != null) && (largeFiles.Count() > 0))
    /// Loops through the large files
    foreach (var file in largeFiles)
        /// Displays file name and size.
        Console.WriteLine(“File: {0} – Size: {1}”, file.Name, file.Length);

LINQ is not searching files in the FileSystem but based on a collection retrieved by the GetFiles method uses its syntax to filter each file based on the size (greater than 100k).

Enjoy it!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: