Advertisement
Guest User

Filedirsearcher By Elektro

a guest
Feb 14th, 2015
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 45.16 KB | None | 0 0
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 14-February-2015
  4. ' ***********************************************************************
  5. ' <copyright file="FileDirSearcher.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. 'Dim files As List(Of FileInfo) = FileDirSearcher.GetFiles("C:\Windows\System32", SearchOption.AllDirectories).ToList
  13. 'Dim files As List(Of String) = FileDirSearcher.GetFilePaths("C:\Windows\System32", SearchOption.AllDirectories).ToList
  14.  
  15. 'Dim dirs As List(Of DirectoryInfo) = FileDirSearcher.GetDirs("C:\Windows\System32", SearchOption.AllDirectories).ToList
  16. 'Dim dirs As List(Of String) = FileDirSearcher.GetDirPaths("C:\Windows\System32", SearchOption.AllDirectories).ToList
  17.  
  18. 'Dim files As IEnumerable(Of FileInfo) = FileDirSearcher.GetFiles(dirPath:="C:\Windows\System32",
  19. '                                                                 searchOption:=SearchOption.TopDirectoryOnly,
  20. '                                                                 fileNamePatterns:={"*"},
  21. '                                                                 fileExtPatterns:={"*.dll", "*.exe"},
  22. '                                                                 ignoreCase:=True,
  23. '                                                                 throwOnError:=True)
  24.  
  25. 'Dim dirs As IEnumerable(Of DirectoryInfo) = FileDirSearcher.GetDirs(dirPath:="C:\Windows\System32",
  26. '                                                                    searchOption:=SearchOption.TopDirectoryOnly,
  27. '                                                                    dirPathPatterns:={"*"},
  28. '                                                                    dirNamePatterns:={"*Microsoft*"},
  29. '                                                                    ignoreCase:=True,
  30. '                                                                    throwOnError:=True)
  31.  
  32. #End Region
  33.  
  34. #Region " Option Statements "
  35.  
  36. Option Explicit On
  37. Option Strict On
  38. Option Infer Off
  39.  
  40. #End Region
  41.  
  42. #Region " Imports "
  43.  
  44. Imports System.IO
  45. Imports System.Collections.Concurrent
  46. Imports System.Threading.Tasks
  47.  
  48. #End Region
  49.  
  50. #Region " File Dir Searcher "
  51.  
  52. ''' <summary>
  53. ''' Searchs for files and directories.
  54. ''' </summary>
  55. Public NotInheritable Class FileDirSearcher
  56.  
  57. #Region " Public Methods "
  58.  
  59.     ''' <summary>
  60.     ''' Gets the files those matches the criteria inside the specified directory and/or sub-directories.
  61.     ''' </summary>
  62.     ''' <param name="dirPath">The root directory path to search for files.</param>
  63.     ''' <param name="searchOption">The searching mode.</param>
  64.     ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  65.     ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  66.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  67.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to file or directory.</param>
  68.     ''' <returns>An <see cref="IEnumerable(Of FileInfo)"/> instance containing the files information.</returns>
  69.     ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  70.     Public Shared Function GetFiles(ByVal dirPath As String,
  71.                                     ByVal searchOption As SearchOption,
  72.                                     Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  73.                                     Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  74.                                     Optional ByVal ignoreCase As Boolean = True,
  75.                                     Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of FileInfo)
  76.  
  77.         ' Analyze and fix path problems.
  78.         ' eg. 'C:' -> 'C:\'
  79.         AnalyzePath(dirPath)
  80.  
  81.         If Not Directory.Exists(dirPath) Then
  82.             Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  83.  
  84.         ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  85.             Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  86.  
  87.         Else ' Get and return the files.
  88.             Dim queue As New ConcurrentQueue(Of FileInfo)
  89.             CollectFiles(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  90.             Return queue.AsEnumerable
  91.  
  92.         End If
  93.  
  94.     End Function
  95.  
  96.     ''' <summary>
  97.     ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  98.     ''' </summary>
  99.     ''' <param name="dirPath">The root directory path to search for files.</param>
  100.     ''' <param name="searchOption">The searching mode.</param>
  101.     ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  102.     ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  103.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  104.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to file or directory.</param>
  105.     ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the filepaths.</returns>
  106.     ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  107.     Public Shared Function GetFilePaths(ByVal dirPath As String,
  108.                                         ByVal searchOption As SearchOption,
  109.                                         Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  110.                                         Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  111.                                         Optional ByVal ignoreCase As Boolean = True,
  112.                                         Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  113.  
  114.         ' Analyze and fix path problems.
  115.         ' eg. 'C:' -> 'C:\'
  116.         AnalyzePath(dirPath)
  117.  
  118.         If Not Directory.Exists(dirPath) Then
  119.             Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  120.  
  121.         ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  122.             Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  123.  
  124.         Else ' Get and return the filepaths.
  125.             Dim queue As New ConcurrentQueue(Of String)
  126.             CollectFilePaths(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  127.             Return queue.AsEnumerable
  128.  
  129.         End If
  130.  
  131.     End Function
  132.  
  133.     ''' <summary>
  134.     ''' Gets the directories those matches the criteria inside the specified directory and/or sub-directories.
  135.     ''' </summary>
  136.     ''' <param name="dirPath">The root directory path to search for directories.</param>
  137.     ''' <param name="searchOption">The searching mode.</param>
  138.     ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  139.     ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  140.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  141.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to directory.</param>
  142.     ''' <returns>An <see cref="IEnumerable(Of DirectoryInfo)"/> instance containing the dirrectories information.</returns>
  143.     ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  144.     Public Shared Function GetDirs(ByVal dirPath As String,
  145.                                    ByVal searchOption As SearchOption,
  146.                                    Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  147.                                    Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  148.                                    Optional ByVal ignoreCase As Boolean = True,
  149.                                    Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of DirectoryInfo)
  150.  
  151.         ' Analyze and fix path problems.
  152.         ' eg. 'C:' -> 'C:\'
  153.         AnalyzePath(dirPath)
  154.  
  155.         If Not Directory.Exists(dirPath) Then
  156.             Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  157.  
  158.         ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  159.             Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  160.  
  161.         Else ' Get and return the files.
  162.             Dim queue As New ConcurrentQueue(Of DirectoryInfo)
  163.             CollectDirs(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  164.             Return queue.AsEnumerable
  165.  
  166.         End If
  167.  
  168.     End Function
  169.  
  170.     ''' <summary>
  171.     ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  172.     ''' </summary>
  173.     ''' <param name="dirPath">The root directory path to search for directories.</param>
  174.     ''' <param name="searchOption">The searching mode.</param>
  175.     ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  176.     ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  177.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  178.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to directory.</param>
  179.     ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the directory paths.</returns>
  180.     ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  181.     Public Shared Function GetDirPaths(ByVal dirPath As String,
  182.                                        ByVal searchOption As SearchOption,
  183.                                        Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  184.                                        Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  185.                                        Optional ByVal ignoreCase As Boolean = True,
  186.                                        Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  187.  
  188.         ' Analyze and fix path problems.
  189.         ' eg. 'C:' -> 'C:\'
  190.         AnalyzePath(dirPath)
  191.  
  192.         If Not Directory.Exists(dirPath) Then
  193.             Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  194.  
  195.         ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  196.             Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  197.  
  198.         Else ' Get and return the filepaths.
  199.             Dim queue As New ConcurrentQueue(Of String)
  200.             CollectDirPaths(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  201.             Return queue.AsEnumerable
  202.  
  203.         End If
  204.  
  205.     End Function
  206.  
  207. #End Region
  208.  
  209. #Region " Private Methods "
  210.  
  211.     ''' <summary>
  212.     ''' Analyzes a directory path and perform specific changes on it.
  213.     ''' </summary>
  214.     ''' <param name="dirPath">The directory path.</param>
  215.     ''' <exception cref="System.ArgumentNullException">dirPath;Value is null, empty, or white-spaced.</exception>
  216.     Private Shared Sub AnalyzePath(ByRef dirPath As String)
  217.  
  218.         If String.IsNullOrEmpty(dirPath) OrElse String.IsNullOrWhiteSpace(dirPath) Then
  219.             Throw New ArgumentNullException("dirPath", "Value is null, empty, or white-spaced.")
  220.  
  221.         Else
  222.             ' Trim unwanted characters.
  223.             dirPath = dirPath.TrimStart({" "c}).TrimEnd({" "c})
  224.  
  225.             If Path.IsPathRooted(dirPath) Then
  226.                 ' The root paths contained on the returned FileInfo objects will start with the same string-case as this root path.
  227.                 ' So just for a little visual improvement, I'll treat this root path as a Drive-Letter and I convert it to UpperCase.
  228.                 dirPath = Char.ToUpper(dirPath.First) & dirPath.Substring(1)
  229.             End If
  230.  
  231.             If Not dirPath.EndsWith("\"c) Then
  232.                 ' Possibly its a drive letter without backslash ('C:') or else just a normal path without backslash ('C\Dir').
  233.                 ' In any case, fix the ending backslash.
  234.                 dirPath = dirPath.Insert(dirPath.Length, "\"c)
  235.             End If
  236.  
  237.         End If
  238.  
  239.     End Sub
  240.  
  241.     ''' <summary>
  242.     ''' Collects the files those matches the criteria inside the specified directory and/or sub-directories.
  243.     ''' </summary>
  244.     ''' <param name="queue">The <see cref="ConcurrentQueue(Of FileInfo)"/> instance to enqueue new files.</param>
  245.     ''' <param name="dirPath">The root directory path to search for files.</param>
  246.     ''' <param name="searchOption">The searching mode.</param>
  247.     ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  248.     ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  249.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  250.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to file or directory.</param>
  251.     Private Shared Sub CollectFiles(ByVal queue As ConcurrentQueue(Of FileInfo),
  252.                                     ByVal dirPath As String,
  253.                                     ByVal searchOption As SearchOption,
  254.                                     ByVal fileNamePatterns As IEnumerable(Of String),
  255.                                     ByVal fileExtPatterns As IEnumerable(Of String),
  256.                                     ByVal ignoreCase As Boolean,
  257.                                     ByVal throwOnError As Boolean)
  258.  
  259.         ' Initialize a DirectoryInfo.
  260.         Dim dirInfo As DirectoryInfo = Nothing
  261.  
  262.         ' Initialize a FileInfo collection.
  263.         Dim fileInfoCol As IEnumerable(Of FileInfo) = Nothing
  264.  
  265.         Try ' Set up a new DirectoryInfo instance using the passed directory path.
  266.             dirInfo = New DirectoryInfo(dirPath)
  267.  
  268.         Catch ex As ArgumentNullException
  269.             If throwOnError Then
  270.                 Throw
  271.             End If
  272.  
  273.         Catch ex As ArgumentException
  274.             If throwOnError Then
  275.                 Throw
  276.             End If
  277.  
  278.         Catch ex As Security.SecurityException
  279.             If throwOnError Then
  280.                 Throw
  281.             End If
  282.  
  283.         Catch ex As PathTooLongException
  284.             If throwOnError Then
  285.                 Throw
  286.             End If
  287.  
  288.         End Try
  289.  
  290.         Try ' Get the top files of the current directory.
  291.  
  292.             If fileExtPatterns IsNot Nothing Then
  293.                 ' Decrease time execution by searching for files that has extension.
  294.                 fileInfoCol = dirInfo.GetFiles("*.*", searchOption.TopDirectoryOnly)
  295.             Else
  296.                 ' Search for all files.
  297.                 fileInfoCol = dirInfo.GetFiles("*", searchOption.TopDirectoryOnly)
  298.             End If
  299.  
  300.         Catch ex As UnauthorizedAccessException
  301.             If throwOnError Then
  302.                 Throw
  303.             End If
  304.  
  305.         Catch ex As DirectoryNotFoundException
  306.             If throwOnError Then
  307.                 Throw
  308.             End If
  309.  
  310.         Catch ex As Exception
  311.             If throwOnError Then
  312.                 Throw
  313.             End If
  314.  
  315.         End Try
  316.  
  317.         ' If the fileInfoCol collection is not empty then...
  318.         If fileInfoCol IsNot Nothing Then
  319.  
  320.             ' Iterate the files.
  321.             For Each fInfo As FileInfo In fileInfoCol
  322.  
  323.                 ' Flag to determine whether a filename pattern is matched.
  324.                 Dim flagNamePattern As Boolean = False
  325.  
  326.                 ' Flag to determine whether a file extension pattern is matched.
  327.                 Dim flagExtPattern As Boolean = False
  328.  
  329.                 ' If filename patterns collection is not empty then...
  330.                 If fileNamePatterns IsNot Nothing Then
  331.  
  332.                     ' Iterate the filename pattern(s).
  333.                     For Each fileNamePattern As String In fileNamePatterns
  334.  
  335.                         ' Match the filename pattern on the current filename.
  336.  
  337.                         ' Supress consecuent conditionals if pattern its an asterisk.
  338.                         If fileNamePattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  339.                             flagNamePattern = True ' Activate the filename flag.
  340.                             Exit For
  341.  
  342.                         ElseIf ignoreCase Then ' Compare filename with ignoring case rules.
  343.                             If fInfo.Name.ToLower Like fileNamePattern.ToLower Then
  344.                                 flagNamePattern = True ' Activate the filename flag.
  345.                                 Exit For
  346.                             End If
  347.  
  348.                         Else ' Compare filename without ignoring case rules.
  349.                             If fInfo.Name Like fileNamePattern Then
  350.                                 flagNamePattern = True ' Activate the filename flag.
  351.                                 Exit For
  352.                             End If
  353.  
  354.                         End If ' ignoreCase
  355.  
  356.                     Next fileNamePattern
  357.  
  358.                 Else ' filename patterns collection is empty.
  359.                     flagNamePattern = True ' Activate the filename flag.
  360.  
  361.                 End If ' fileNamePatterns IsNot Nothing
  362.  
  363.                 ' If file extension patterns collection is not empty then...
  364.                 If fileExtPatterns IsNot Nothing Then
  365.  
  366.                     ' Iterate the file extension pattern(s).
  367.                     For Each fileExtPattern As String In fileExtPatterns
  368.  
  369.                         ' Match the file extension pattern on the current file extension.
  370.  
  371.                         ' Supress consecuent conditionals if pattern its an asterisk.
  372.                         If fileExtPattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  373.                             flagExtPattern = True ' Activate the file extension flag.
  374.                             Exit For
  375.  
  376.                         ElseIf ignoreCase Then ' Compare filename with ignoring case rules.
  377.                             If fInfo.Extension.ToLower Like fileExtPattern.ToLower Then
  378.                                 flagExtPattern = True ' Activate the file extension flag.
  379.                                 Exit For
  380.                             End If
  381.  
  382.                         Else ' Compare filename without ignoring case rules.
  383.                             If fInfo.Extension Like fileExtPattern Then
  384.                                 flagExtPattern = True ' Activate the file extension flag.
  385.                                 Exit For
  386.                             End If
  387.  
  388.                         End If
  389.  
  390.                     Next fileExtPattern
  391.  
  392.                 Else  ' file extension patterns collection is empty.
  393.                     flagExtPattern = True ' Activate the file extension flag.
  394.  
  395.                 End If ' fileExtPatterns IsNot Nothing
  396.  
  397.                 ' If fileName and also fileExtension patterns are matched then...
  398.                 If flagNamePattern AndAlso flagExtPattern Then
  399.                     queue.Enqueue(fInfo) ' Enqueue this FileInfo object.
  400.                 End If
  401.  
  402.             Next fInfo
  403.  
  404.         End If ' fileInfoCol IsNot Nothing
  405.  
  406.         ' If searchOption is recursive then...
  407.         If searchOption = searchOption.AllDirectories Then
  408.  
  409.             Try
  410.                 ' Try next iterations.
  411.                 Task.WaitAll(dirInfo.GetDirectories.
  412.                              Select(Function(dir As DirectoryInfo)
  413.                                         Return Task.Factory.StartNew(Sub()
  414.                                                                          CollectFiles(queue,
  415.                                                                                       dir.FullName, searchOption.AllDirectories,
  416.                                                                                       fileNamePatterns, fileExtPatterns,
  417.                                                                                       ignoreCase, throwOnError)
  418.                                                                      End Sub)
  419.                                     End Function).ToArray)
  420.  
  421.             Catch ex As UnauthorizedAccessException
  422.                 If throwOnError Then
  423.                     Throw
  424.                 End If
  425.  
  426.             Catch ex As DirectoryNotFoundException
  427.                 If throwOnError Then
  428.                     Throw
  429.                 End If
  430.  
  431.             Catch ex As Exception
  432.                 If throwOnError Then
  433.                     Throw
  434.                 End If
  435.  
  436.             End Try
  437.  
  438.         End If ' searchOption = searchOption.AllDirectories
  439.  
  440.     End Sub
  441.  
  442.     ''' <summary>
  443.     ''' Collects the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  444.     ''' </summary>
  445.     ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new filepaths.</param>
  446.     ''' <param name="dirPath">The root directory path to search for files.</param>
  447.     ''' <param name="searchOption">The searching mode.</param>
  448.     ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  449.     ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  450.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  451.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to file or directory.</param>
  452.     Private Shared Sub CollectFilePaths(ByVal queue As ConcurrentQueue(Of String),
  453.                                         ByVal dirPath As String,
  454.                                         ByVal searchOption As SearchOption,
  455.                                         ByVal fileNamePatterns As IEnumerable(Of String),
  456.                                         ByVal fileExtPatterns As IEnumerable(Of String),
  457.                                         ByVal ignoreCase As Boolean,
  458.                                         ByVal throwOnError As Boolean)
  459.  
  460.         ' Initialize a filepath collection.
  461.         Dim filePathCol As IEnumerable(Of String) = Nothing
  462.  
  463.         Try ' Get the top files of the current directory.
  464.  
  465.             If fileExtPatterns IsNot Nothing Then
  466.                 ' Decrease time execution by searching for files that has extension.
  467.                 filePathCol = Directory.GetFiles(dirPath, "*.*", searchOption.TopDirectoryOnly)
  468.             Else
  469.                 ' Search for all files.
  470.                 filePathCol = Directory.GetFiles(dirPath, "*", searchOption.TopDirectoryOnly)
  471.             End If
  472.  
  473.         Catch ex As UnauthorizedAccessException
  474.             If throwOnError Then
  475.                 Throw
  476.             End If
  477.  
  478.         Catch ex As DirectoryNotFoundException
  479.             If throwOnError Then
  480.                 Throw
  481.             End If
  482.  
  483.         Catch ex As Exception
  484.             If throwOnError Then
  485.                 Throw
  486.             End If
  487.  
  488.         End Try
  489.  
  490.         ' If the filepath collection is not empty then...
  491.         If filePathCol IsNot Nothing Then
  492.  
  493.             ' Iterate the filepaths.
  494.             For Each filePath As String In filePathCol
  495.  
  496.                 ' Flag to determine whether a filename pattern is matched.
  497.                 Dim flagNamePattern As Boolean = False
  498.  
  499.                 ' Flag to determine whether a file extension pattern is matched.
  500.                 Dim flagExtPattern As Boolean = False
  501.  
  502.                 ' If filename patterns collection is not empty then...
  503.                 If fileNamePatterns IsNot Nothing Then
  504.  
  505.                     ' Iterate the filename pattern(s).
  506.                     For Each fileNamePattern As String In fileNamePatterns
  507.  
  508.                         ' Match the filename pattern on the current filename.
  509.  
  510.                         ' Supress consecuent conditionals if pattern its an asterisk.
  511.                         If fileNamePattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  512.                             flagNamePattern = True ' Activate the filename flag.
  513.                             Exit For
  514.  
  515.                         ElseIf ignoreCase Then ' Compare filename with ignoring case rules.
  516.                             If Path.GetFileNameWithoutExtension(filePath).ToLower Like fileNamePattern.ToLower Then
  517.                                 flagNamePattern = True ' Activate the filename flag.
  518.                                 Exit For
  519.                             End If
  520.  
  521.                         Else ' Compare filename without ignoring case rules.
  522.                             If Path.GetFileNameWithoutExtension(filePath) Like fileNamePattern Then
  523.                                 flagNamePattern = True ' Activate the filename flag.
  524.                                 Exit For
  525.                             End If
  526.  
  527.                         End If ' ignoreCase
  528.  
  529.                     Next fileNamePattern
  530.  
  531.                 Else ' filename patterns collection is empty.
  532.                     flagNamePattern = True ' Activate the filename flag.
  533.  
  534.                 End If ' fileNamePatterns IsNot Nothing
  535.  
  536.                 ' If file extension patterns collection is not empty then...
  537.                 If fileExtPatterns IsNot Nothing Then
  538.  
  539.                     ' Iterate the file extension pattern(s).
  540.                     For Each fileExtPattern As String In fileExtPatterns
  541.  
  542.                         ' Match the file extension pattern on the current file extension.
  543.  
  544.                         ' Supress consecuent conditionals if pattern its an asterisk.
  545.                         If fileExtPattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  546.                             flagExtPattern = True ' Activate the file extension flag.
  547.                             Exit For
  548.  
  549.                         ElseIf ignoreCase Then ' Compare filename with ignoring case rules.
  550.                             If Path.GetExtension(filePath).ToLower Like fileExtPattern.ToLower Then
  551.                                 flagExtPattern = True ' Activate the file extension flag.
  552.                                 Exit For
  553.                             End If
  554.  
  555.                         Else ' Compare filename without ignoring case rules.
  556.                             If Path.GetExtension(filePath) Like fileExtPattern Then
  557.                                 flagExtPattern = True ' Activate the file extension flag.
  558.                                 Exit For
  559.                             End If
  560.  
  561.                         End If
  562.  
  563.                     Next fileExtPattern
  564.  
  565.                 Else  ' file extension patterns collection is empty.
  566.                     flagExtPattern = True ' Activate the file extension flag.
  567.  
  568.                 End If ' fileExtPatterns IsNot Nothing
  569.  
  570.                 ' If fileName and also fileExtension patterns are matched then...
  571.                 If flagNamePattern AndAlso flagExtPattern Then
  572.                     queue.Enqueue(filePath) ' Enqueue this filepath.
  573.                 End If
  574.  
  575.             Next filePath
  576.  
  577.         End If ' filePathCol IsNot Nothing
  578.  
  579.         ' If searchOption is recursive then...
  580.         If searchOption = searchOption.AllDirectories Then
  581.  
  582.             Try
  583.                 ' Try next iterations.
  584.                 Task.WaitAll(New DirectoryInfo(dirPath).GetDirectories.
  585.                                  Select(Function(dir As DirectoryInfo)
  586.                                             Return Task.Factory.StartNew(Sub()
  587.                                                                              CollectFilePaths(queue,
  588.                                                                                               dir.FullName, searchOption.AllDirectories,
  589.                                                                                               fileNamePatterns, fileExtPatterns,
  590.                                                                                               ignoreCase, throwOnError)
  591.                                                                          End Sub)
  592.                                         End Function).ToArray)
  593.  
  594.             Catch ex As UnauthorizedAccessException
  595.                 If throwOnError Then
  596.                     Throw
  597.                 End If
  598.  
  599.             Catch ex As DirectoryNotFoundException
  600.                 If throwOnError Then
  601.                     Throw
  602.                 End If
  603.  
  604.             Catch ex As Exception
  605.                 If throwOnError Then
  606.                     Throw
  607.                 End If
  608.  
  609.             End Try
  610.  
  611.         End If ' searchOption = searchOption.AllDirectories
  612.  
  613.     End Sub
  614.  
  615.     ''' <summary>
  616.     ''' Collects the directories those matches the criteria inside the specified directory and/or sub-directories.
  617.     ''' </summary>
  618.     ''' <param name="queue">The <see cref="ConcurrentQueue(Of DirectoryInfo)"/> instance to enqueue new directories.</param>
  619.     ''' <param name="dirPath">The root directory path to search for directories.</param>
  620.     ''' <param name="searchOption">The searching mode.</param>
  621.     ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  622.     ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  623.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  624.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to directory.</param>
  625.     Private Shared Sub CollectDirs(ByVal queue As ConcurrentQueue(Of DirectoryInfo),
  626.                                    ByVal dirPath As String,
  627.                                    ByVal searchOption As SearchOption,
  628.                                    ByVal dirPathPatterns As IEnumerable(Of String),
  629.                                    ByVal dirNamePatterns As IEnumerable(Of String),
  630.                                    ByVal ignoreCase As Boolean,
  631.                                    ByVal throwOnError As Boolean)
  632.  
  633.         ' Initialize a DirectoryInfo.
  634.         Dim dirInfo As DirectoryInfo = Nothing
  635.  
  636.         ' Initialize a DirectoryInfo collection.
  637.         Dim dirInfoCol As IEnumerable(Of DirectoryInfo) = Nothing
  638.  
  639.         Try ' Set up a new DirectoryInfo instance using the passed directory path.
  640.             dirInfo = New DirectoryInfo(dirPath)
  641.  
  642.         Catch ex As ArgumentNullException
  643.             If throwOnError Then
  644.                 Throw
  645.             End If
  646.  
  647.         Catch ex As ArgumentException
  648.             If throwOnError Then
  649.                 Throw
  650.             End If
  651.  
  652.         Catch ex As Security.SecurityException
  653.             If throwOnError Then
  654.                 Throw
  655.             End If
  656.  
  657.         Catch ex As PathTooLongException
  658.             If throwOnError Then
  659.                 Throw
  660.             End If
  661.  
  662.         End Try
  663.  
  664.         Try ' Get the top directories of the current directory.
  665.             dirInfoCol = dirInfo.GetDirectories("*", searchOption.TopDirectoryOnly)
  666.  
  667.         Catch ex As UnauthorizedAccessException
  668.             If throwOnError Then
  669.                 Throw
  670.             End If
  671.  
  672.         Catch ex As DirectoryNotFoundException
  673.             If throwOnError Then
  674.                 Throw
  675.             End If
  676.  
  677.         Catch ex As Exception
  678.             If throwOnError Then
  679.                 Throw
  680.             End If
  681.  
  682.         End Try
  683.  
  684.         ' If the fileInfoCol collection is not empty then...
  685.         If dirInfoCol IsNot Nothing Then
  686.  
  687.             ' Iterate the files.
  688.             For Each dir As DirectoryInfo In dirInfoCol
  689.  
  690.                 ' Flag to determine whether a directory path pattern is matched.
  691.                 Dim flagPathPattern As Boolean = False
  692.  
  693.                 ' Flag to determine whether a directory name pattern is matched.
  694.                 Dim flagNamePattern As Boolean = False
  695.  
  696.                 ' If directory path patterns collection is not empty then...
  697.                 If dirPathPatterns IsNot Nothing Then
  698.  
  699.                     ' Iterate the directory path pattern(s).
  700.                     For Each dirpathPattern As String In dirPathPatterns
  701.  
  702.                         ' Match the directory path pattern on the current filename.
  703.  
  704.                         ' Supress consecuent conditionals if pattern its an asterisk.
  705.                         If dirpathPattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  706.                             flagPathPattern = True ' Activate the directory path flag.
  707.                             Exit For
  708.  
  709.                         ElseIf ignoreCase Then ' Compare directory path with ignoring case rules.
  710.                             If dir.FullName.ToLower Like dirpathPattern.ToLower Then
  711.                                 flagPathPattern = True ' Activate the directory path flag.
  712.                                 Exit For
  713.                             End If
  714.  
  715.                         Else ' Compare directory path without ignoring case rules.
  716.                             If dir.FullName Like dirpathPattern Then
  717.                                 flagPathPattern = True ' Activate the directory path flag.
  718.                                 Exit For
  719.                             End If
  720.  
  721.                         End If ' ignoreCase
  722.  
  723.                     Next dirpathPattern
  724.  
  725.                 Else ' directory path patterns collection is empty.
  726.                     flagPathPattern = True ' Activate the directory path flag.
  727.  
  728.                 End If ' dirpathPatterns IsNot Nothing
  729.  
  730.                 ' If directory name patterns collection is not empty then...
  731.                 If dirNamePatterns IsNot Nothing Then
  732.  
  733.                     ' Iterate the directory name pattern(s).
  734.                     For Each dirNamePattern As String In dirNamePatterns
  735.  
  736.                         ' Match the directory name pattern on the current filename.
  737.  
  738.                         ' Supress consecuent conditionals if pattern its an asterisk.
  739.                         If dirNamePattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  740.                             flagNamePattern = True ' Activate the directory name flag.
  741.                             Exit For
  742.  
  743.                         ElseIf ignoreCase Then ' Compare directory name with ignoring case rules.
  744.                             If dir.Name.ToLower Like dirNamePattern.ToLower Then
  745.                                 flagNamePattern = True ' Activate the directory name flag.
  746.                                 Exit For
  747.                             End If
  748.  
  749.                         Else ' Compare directory name without ignoring case rules.
  750.                             If dir.Name Like dirNamePattern Then
  751.                                 flagNamePattern = True ' Activate the directory name flag.
  752.                                 Exit For
  753.                             End If
  754.  
  755.                         End If ' ignoreCase
  756.  
  757.                     Next dirNamePattern
  758.  
  759.                 Else ' directory name patterns collection is empty.
  760.                     flagNamePattern = True ' Activate the filename flag.
  761.  
  762.                 End If ' dirNamePatterns IsNot Nothing
  763.  
  764.                 ' If directory path and also directory name patterns are matched then...
  765.                 If flagPathPattern AndAlso flagNamePattern Then
  766.                     queue.Enqueue(dir) ' Enqueue this DirectoryInfo object.
  767.                 End If
  768.  
  769.             Next dir
  770.  
  771.         End If ' dirInfoCol IsNot Nothing
  772.  
  773.         ' If searchOption is recursive then...
  774.         If searchOption = searchOption.AllDirectories Then
  775.  
  776.             Try
  777.                 ' Try next iterations.
  778.                 Task.WaitAll(dirInfo.GetDirectories.
  779.                              Select(Function(dir As DirectoryInfo)
  780.                                         Return Task.Factory.StartNew(Sub()
  781.                                                                          CollectDirs(queue,
  782.                                                                                      dir.FullName, searchOption.AllDirectories,
  783.                                                                                      dirPathPatterns, dirNamePatterns,
  784.                                                                                      ignoreCase, throwOnError)
  785.                                                                      End Sub)
  786.                                     End Function).ToArray)
  787.  
  788.             Catch ex As UnauthorizedAccessException
  789.                 If throwOnError Then
  790.                     Throw
  791.                 End If
  792.  
  793.             Catch ex As DirectoryNotFoundException
  794.                 If throwOnError Then
  795.                     Throw
  796.                 End If
  797.  
  798.             Catch ex As Exception
  799.                 If throwOnError Then
  800.                     Throw
  801.                 End If
  802.  
  803.             End Try
  804.  
  805.         End If ' searchOption = searchOption.AllDirectories
  806.  
  807.     End Sub
  808.  
  809.     ''' <summary>
  810.     ''' Collects the directory paths those matches the criteria inside the specified directory and/or sub-directories.
  811.     ''' </summary>
  812.     ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new directory paths.</param>
  813.     ''' <param name="dirPath">The root directory path to search for directories.</param>
  814.     ''' <param name="searchOption">The searching mode.</param>
  815.     ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  816.     ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  817.     ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  818.     ''' <param name="throwOnError">Determines whether exceptions will be thrown, like access denied to directory.</param>
  819.     Private Shared Sub CollectDirPaths(ByVal queue As ConcurrentQueue(Of String),
  820.                                        ByVal dirPath As String,
  821.                                        ByVal searchOption As SearchOption,
  822.                                        ByVal dirPathPatterns As IEnumerable(Of String),
  823.                                        ByVal dirNamePatterns As IEnumerable(Of String),
  824.                                        ByVal ignoreCase As Boolean,
  825.                                        ByVal throwOnError As Boolean)
  826.  
  827.         ' Initialize a directory paths collection.
  828.         Dim dirPathCol As IEnumerable(Of String) = Nothing
  829.  
  830.         Try ' Get the top directories of the current directory.
  831.             dirPathCol = Directory.GetDirectories(dirPath, "*", searchOption.TopDirectoryOnly)
  832.  
  833.         Catch ex As UnauthorizedAccessException
  834.             If throwOnError Then
  835.                 Throw
  836.             End If
  837.  
  838.         Catch ex As DirectoryNotFoundException
  839.             If throwOnError Then
  840.                 Throw
  841.             End If
  842.  
  843.         Catch ex As Exception
  844.             If throwOnError Then
  845.                 Throw
  846.             End If
  847.  
  848.         End Try
  849.  
  850.         ' If the fileInfoCol collection is not empty then...
  851.         If dirPathCol IsNot Nothing Then
  852.  
  853.             ' Iterate the files.
  854.             For Each dir As String In dirPathCol
  855.  
  856.                 ' Flag to determine whether a directory path pattern is matched.
  857.                 Dim flagPathPattern As Boolean = False
  858.  
  859.                 ' Flag to determine whether a directory name pattern is matched.
  860.                 Dim flagNamePattern As Boolean = False
  861.  
  862.                 ' If directory path patterns collection is not empty then...
  863.                 If dirPathPatterns IsNot Nothing Then
  864.  
  865.                     ' Iterate the directory path pattern(s).
  866.                     For Each dirpathPattern As String In dirPathPatterns
  867.  
  868.                         ' Match the directory path pattern on the current filename.
  869.  
  870.                         ' Supress consecuent conditionals if pattern its an asterisk.
  871.                         If dirpathPattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  872.                             flagPathPattern = True ' Activate the directory path flag.
  873.                             Exit For
  874.  
  875.                         ElseIf ignoreCase Then ' Compare directory path with ignoring case rules.
  876.                             If dir.ToLower Like dirpathPattern.ToLower Then
  877.                                 flagPathPattern = True ' Activate the directory path flag.
  878.                                 Exit For
  879.                             End If
  880.  
  881.                         Else ' Compare directory path without ignoring case rules.
  882.                             If dir Like dirpathPattern Then
  883.                                 flagPathPattern = True ' Activate the directory path flag.
  884.                                 Exit For
  885.                             End If
  886.  
  887.                         End If ' ignoreCase
  888.  
  889.                     Next dirpathPattern
  890.  
  891.                 Else ' directory path patterns collection is empty.
  892.                     flagPathPattern = True ' Activate the directory path flag.
  893.  
  894.                 End If ' dirpathPatterns IsNot Nothing
  895.  
  896.                 ' If directory name patterns collection is not empty then...
  897.                 If dirNamePatterns IsNot Nothing Then
  898.  
  899.                     ' Iterate the directory name pattern(s).
  900.                     For Each dirNamePattern As String In dirNamePatterns
  901.  
  902.                         ' Match the directory name pattern on the current filename.
  903.  
  904.                         ' Supress consecuent conditionals if pattern its an asterisk.
  905.                         If dirNamePattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  906.                             flagNamePattern = True ' Activate the directory name flag.
  907.                             Exit For
  908.  
  909.                         ElseIf ignoreCase Then ' Compare directory name with ignoring case rules.
  910.                             If Path.GetFileName(dir).ToLower Like dirNamePattern.ToLower Then
  911.                                 flagNamePattern = True ' Activate the directory name flag.
  912.                                 Exit For
  913.                             End If
  914.  
  915.                         Else ' Compare directory name without ignoring case rules.
  916.                             If Path.GetFileName(dir) Like dirNamePattern Then
  917.                                 flagNamePattern = True ' Activate the directory name flag.
  918.                                 Exit For
  919.                             End If
  920.  
  921.                         End If ' ignoreCase
  922.  
  923.                     Next dirNamePattern
  924.  
  925.                 Else ' directory name patterns collection is empty.
  926.                     flagNamePattern = True ' Activate the filename flag.
  927.  
  928.                 End If ' dirNamePatterns IsNot Nothing
  929.  
  930.                 ' If directory path and also directory name patterns are matched then...
  931.                 If flagPathPattern AndAlso flagNamePattern Then
  932.                     queue.Enqueue(dir) ' Enqueue this directory path.
  933.                 End If
  934.  
  935.             Next dir
  936.  
  937.         End If ' dirPathCol IsNot Nothing
  938.  
  939.         ' If searchOption is recursive then...
  940.         If searchOption = searchOption.AllDirectories Then
  941.  
  942.             Try
  943.                 ' Try next iterations.
  944.                 Task.WaitAll(New DirectoryInfo(dirPath).GetDirectories.
  945.                                  Select(Function(dir As DirectoryInfo)
  946.                                             Return Task.Factory.StartNew(Sub()
  947.                                                                              CollectDirPaths(queue,
  948.                                                                                          dir.FullName, searchOption.AllDirectories,
  949.                                                                                          dirPathPatterns, dirNamePatterns,
  950.                                                                                          ignoreCase, throwOnError)
  951.                                                                          End Sub)
  952.                                         End Function).ToArray)
  953.  
  954.             Catch ex As UnauthorizedAccessException
  955.                 If throwOnError Then
  956.                     Throw
  957.                 End If
  958.  
  959.             Catch ex As DirectoryNotFoundException
  960.                 If throwOnError Then
  961.                     Throw
  962.                 End If
  963.  
  964.             Catch ex As Exception
  965.                 If throwOnError Then
  966.                     Throw
  967.                 End If
  968.  
  969.             End Try
  970.  
  971.         End If ' searchOption = searchOption.AllDirectories
  972.  
  973.     End Sub
  974.  
  975. #End Region
  976.  
  977. End Class
  978.  
  979. #End Region
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement