System.IO DirectoryInfo extensions

I have built some extensions to System.IO class DirectoryInfo


GetFiles extension fetches files that match a regular expression either in the name or content.

CopyTo extension copies the files and folders to the destination specified, overwriting if specified.

FileDiff extension gets the difference is the files (by name) between 2 directories. inBoth output parameter contains files common to both, inA contains files only in the A, and inB contains files only in B.

CompareFilesTo extension compares 2 directories for their files (by name) and returns 1 if number of files in dirA is greater thn dirB, -1 if reversed and 0 if equal.

GetDirectories extension fetches directories by a specified sort order (IComparer).

Extensions :

 
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.IO;
using
System.Runtime.InteropServices;
using
System.Text.RegularExpressions;

namespace
System.IO
{
   public static class ExtensionMethods
   {

      #region
Enumerators
      public enum Option
      {
         SearchContent = 0,
         SearchTitle = 1,
         SearchTitleAndContent = 2
      }

      #endregion

      #region
Internal Classes
      internal class FileInfoComparer : IEqualityComparer<FileInfo>
      {
         public bool Equals(FileInfo a, FileInfo b)
         {
            return a.FullName == b.FullName;
         }
         public int GetHashCode(FileInfo fi)
         {
            return fi.GetHashCode();
         }
      }

      #endregion

      #region
Public Methods
      public static FileInfo[] GetFiles(this DirectoryInfo DirectoryInfoObject, string searchPattern, Option option, SearchOption searchOption)
      {
         List<FileInfo> matchedFiles = new List<FileInfo>();
         if (searchOption == SearchOption.AllDirectories)
         {
            foreach (DirectoryInfo di in DirectoryInfoObject.GetDirectories())
            {
               matchedFiles.AddRange(di.GetFiles(searchPattern, option,
SearchOption.AllDirectories).ToList());
            }
         }
         FileInfoComparer comparer = new FileInfoComparer();
         if (option == Option.SearchContent || option == Option.SearchTitleAndContent)
         {
            foreach (FileInfo fi in DirectoryInfoObject.GetFiles())
            {
               StreamReader sr = new StreamReader(fi.FullName);
               if (Regex.Match(sr.ReadToEnd(), searchPattern).Success)
                  if (!matchedFiles.Contains(fi, comparer))
                     matchedFiles.Add(fi);
            }
         }
         if (option == Option.SearchTitle || option == Option.SearchTitleAndContent)
         {
            foreach (FileInfo fi in DirectoryInfoObject.GetFiles())
            {
               if (Regex.Match(fi.Name, searchPattern).Success)
                  if (!matchedFiles.Contains(fi, comparer))
                     matchedFiles.Add(fi);
            }
         }
         return matchedFiles.ToArray();
      }

      public static void CopyTo(this DirectoryInfo DirectoryInfoObject, string DestinationDirectoryPath, bool Overwrite)
      {
         if (Overwrite)
         {
            Directory.Delete(DestinationDirectoryPath, true);
         }
         CopyHelper(DirectoryInfoObject, DestinationDirectoryPath, Overwrite);
      }
      public static void FileDiff(this DirectoryInfo dirA, DirectoryInfo dirB, out FileInfo[] inBoth, out FileInfo[] inA, out FileInfo[] inB)
      {
         var inDirBoth = from file in dirA.GetFiles().ToList()
                           join file1 in dirB.GetFiles().ToList() on file.Name equals file1.Name
                           select file;
         var inDirAOnly = from file in dirA.GetFiles().ToList()
                           join file1 in dirB.GetFiles().ToList() on file.Name equals file1.Name
                           into diff
                           from file2 in diff.DefaultIfEmpty()
                           where file2 == null
                           select file;
         var inDirBOnly = from file in dirB.GetFiles().ToList()
                           join file1 in dirA.GetFiles().ToList() on file.Name equals file1.Name
                           into diff
                           from file2 in diff.DefaultIfEmpty()
                           where file2 == null
                           select file;
         inBoth = inDirBoth.ToArray();
         inA = inDirAOnly.ToArray();
         inB = inDirBOnly.ToArray();
      }
      public static int CompareFilesTo(this DirectoryInfo dirA, DirectoryInfo dirB)
      {
         var inDirAOnly = from file in dirA.GetFiles().ToList()
                           join file1 in dirB.GetFiles().ToList() on file.Name equals file1.Name
                           into diff
                           from file2 in diff.DefaultIfEmpty()
                           where file2 == null
                           select file;
         var inDirBOnly = from file in dirB.GetFiles().ToList()
                           join file1 in dirA.GetFiles().ToList() on file.Name equals file1.Name
                           into diff
                           from file2 in diff.DefaultIfEmpty()
                           where file2 == null
                           select file;
         if (inDirAOnly.Count() > inDirBOnly.Count())
            return 1;
         if (inDirAOnly.Count() < inDirBOnly.Count())
            return -1;
         return 0;
      }
      public static DirectoryInfo[] GetDirectories(this DirectoryInfo di, IComparer<DirectoryInfo> comparer)
      {
         List<DirectoryInfo> lstDirectories = new List<DirectoryInfo>(di.GetDirectories());
         lstDirectories.Sort(comparer);
         return lstDirectories.ToArray();
      }
      public static DirectoryInfo[] GetDirectories(this DirectoryInfo di, Comparison<DirectoryInfo> comparer)
      {
         List<DirectoryInfo> lstDirectories = new List<DirectoryInfo>(di.GetDirectories());
         lstDirectories.Sort(comparer);
         return lstDirectories.ToArray();
      }

      #endregion

      #region
Private Methods
      private static void CopyHelper(this DirectoryInfo DirectoryInfoObject, string DestinationDirectoryPath, bool Overwrite)
      {
         if (!Directory.Exists(DestinationDirectoryPath))
            Directory.CreateDirectory(DestinationDirectoryPath);
         foreach (string directory in Directory.GetDirectories(DirectoryInfoObject.FullName))
         {
            DirectoryInfo di = new DirectoryInfo(directory);
            di.CopyHelper(DestinationDirectoryPath +
@"\" + di.Name, Overwrite);
         }
         foreach (string file in Directory.GetFiles(DirectoryInfoObject.FullName))
         {
            FileInfo fi = new FileInfo(file);
            fi.CopyTo(DestinationDirectoryPath +
@"\" + fi.Name, Overwrite);
         }
      }

      #endregion

   }
}

Usage :

 
public class DirectoryComparer : IComparer<DirectoryInfo>
{
   public int Compare(DirectoryInfo x, DirectoryInfo y)
   {
      // if x contains more files than y return 1
      if (x.GetFiles().Count() > y.GetFiles().Count())
      {
         return 1;
      }
      //if x contains less files than y return -1
      if (x.GetFiles().Count() < y.GetFiles().Count())
      {
         return -1;
      }
      //if x contains the same number of files as y then return 0
      return 0;
   }
}





///////////////////////////////////////////////////////////////////////////////////////////////////////
//Copy directory to destination
DirectoryInfo di = new DirectoryInfo(@"c:\Temp\Test");
di.CopyTo(
@"c:\Temp\Test1", true);
///////////////////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////////////////////

//Gets directories in ascending order of the number of files they contain using class DirectoryComparer
//which implements IComparer
DirectoryComparer directoryComparer = new DirectoryComparer();

DirectoryInfo
[] sortedDirectoryInfos = di.GetDirectories(directoryComparer);
///////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////

//comparisonResult is 1 if dirB contains less files, -1 if dirB contains more files, 0 if equal
int comparisonResult = di.CompareFilesTo(new DirectoryInfo(@"c:\Temp\Test1"));
///////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////////

//Gets the files (by name) common to both folders in inBoth, files only in dirA in inA and files only
//in dirB in inB
FileInfo[] inBoth = { };
FileInfo[] inA = { };
FileInfo[] inB = { };


di.FileDiff(
new DirectoryInfo(@"c:\Temp\Test1"), out inBoth, out inA, out inB);
///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
//Get files containing text that matches a specified regular expression
DirectoryInfo di1 = new DirectoryInfo(@"C:\Temp\Test");

FileInfo
[] files = di1.GetFiles(@"Testing|IO", ExtensionMethods.Option.SearchContent , SearchOption.AllDirectories);

FileInfo
[] files1 = di1.GetFiles(@"Test|IO", ExtensionMethods.Option.SearchTitleAndContent, SearchOption.AllDirectories);
///////////////////////////////////////////////////////////////////////////////////////////////////////

Ebook Download
View all
Learn
View all