DevPinoy.org
A Filipino Developers Community
   
Another Real-World Example On When To Use Extension Methods

It's funny, just after posting this post in response to an article that N@rds posted that I realized that I have been preaching about extension methods and his problem was a great example on when to make use of this excellent feature.

Let's start doing some extension methods. N@rds made a wish in his last post which says:

"I wish that on the next release of the framework it would have another overload for System.IO.Directory.GetFiles() something like System.IO.Directory.GetFiles(string,string[]) or System.IO.Directory.GetFiles(string, List<string>)..."

We can wait for Microsoft to add this new overload to the Directory class or we can extend it by addinf extension methods to the Directory class. But there is one small problem, the Directory class is static which means that it can't be passed as a parameter to a function which means that we can't add an extension method to it.

:'( Sad.

Oh wait a minute! There is another class in the System.IO namespace that has similar functionality to the Directory class called DirectoryInfo which is not static. DirectoryInfo exposes instance methods for creating, moving, and enumerating through directories and subdirectories[link]. DirectoryInfo is closely similar to the Directory class which makes it prime candidate to build a workaround for our problem.

Now that we figured out the class to use, it's time to extend it. Below is the class that I have build that shows you an extended GetFiles() and DeleteFiles()  method .

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

namespace KeithRull.Extensions
{
    public static class DirectoryInfoExtensions
    {
        /// <summary>
        /// Get files using the specified pattern
        /// </summary>
        /// <param name="d">the DirectoryInfo object</param>
        /// <param name="listOfSearchPatterns"> the list of search patterns</param>
        /// <returns>returns a list of FileInfo objects</returns>
        public static FileInfo[] GetFiles(this DirectoryInfo d,  
            List<string> listOfSearchPatterns)
        {
            List<FileInfo> matchingFiles = new List<FileInfo>();

            //iterate thru all the search patterns
            foreach (string pattern in listOfSearchPatterns)
            {
                //get the files and add it to our list
                matchingFiles.AddRange(d.GetFiles(pattern));
            }

            //return the selected objects
            return matchingFiles.ToArray();
        }

        /// <summary>
        /// Delete files using a pattern
        /// </summary>
        /// <param name="d">the directory info</param>
        /// <param name="listOfSearchPatterns">the list of search patterns</param>
        public static void DeleteFiles(this DirectoryInfo d
            , List<string> listOfSearchPatterns)
        {
            //get the files to delete that match the pattern
            FileInfo[] matchingFiles = GetFiles(d, listOfSearchPatterns);

            //iterate thru each fileinfo object
            foreach (FileInfo fileToDelete in matchingFiles)
            {
                if (File.Exists(fileToDelete.FullName))
                {
                    //delete the file
                    File.Delete(fileToDelete.FullName);
                }
            }
        }
    }
}

Sample usage would be as follows:

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

using KeithRull.Extensions;

namespace KeithRull.SeachingFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // the directory to get the files from
            string path = @"c:\components\";

            //the list of seach patterns
            List<string> listOfSearchPatterns = new List<string>();
            listOfSearchPatterns.Add("*.xml");
            listOfSearchPatterns.Add("*.dll");

            //create an object that would simbolize our directory
            DirectoryInfo d = new DirectoryInfo(path);
            //get the files
            FileInfo[] matchingFiles = d.GetFiles(listOfSearchPatterns);
            
            //display the results to the console
            foreach (FileInfo file in matchingFiles)
            {
                Console.WriteLine(file.Name);
            }
            
            Console.Read();
        }
    }
}

Here's screenshot of our extension method in action:

Cool! Another real-world problem solved by using extension methods!


Posted 02-04-2008 10:32 AM by keithrull

Comments

System.IO.Directory.GetFiles() does not support multiple search pattern - n@rds wrote System.IO.Directory.GetFiles() does not support multiple search pattern - n@rds
on 02-04-2008 5:22 PM

Pingback from  System.IO.Directory.GetFiles() does not support multiple search pattern - n@rds

jokiz wrote re: Another Real-World Example On When To Use Extension Methods
on 02-07-2008 6:44 PM

hmmm, my approach would be something like: Process.Start("delete *.csv"), hehe


Copyright DevPinoy 2005-2008