elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado:


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  ayuda con manejo de archivos en vb.net 2008
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 [2] Ir Abajo Respuesta Imprimir
Autor Tema: ayuda con manejo de archivos en vb.net 2008  (Leído 8,209 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: ayuda con manejo de archivos en vb.net 2008
« Respuesta #10 en: 22 Septiembre 2017, 13:39 pm »

Umm. no había pensado hacer eso. en verdad podría ser mas optimo , ya que con la solución que encontré tarda mucho.

La metodología propuesta por el compañero NEBIRE de obtener una colección con todos los tipos de archivos e ir filtrando según la extensión, tiene sus ventajas pero también sus desventajas, resultando así en una solución óptima en muchos casos, y en otros no. Todo depende del escenario / circunstancias donde vayas a aplicar esa (o cualquier otra) solución.



la solución que encontré tarda mucho.

Si el rendimiento (en general, como la velocidad de ejecución) es un factor de importancia para ti, entonces deberías utilizar un tipo de evaluación vaga (o Lazy Evaluation por su nombre en Inglés) como sería la interfáz IEnumerable, y hacer uso de la programación asincrónica o del paralelismo.

Voy a compartir contigo un pequeño extracto del código fuente de mi framework comercial ElektroKit (el cual se puede encontrar en mi firma de usuario del foro). Este código es una implementación personal (bueno, es un wrapper mejorado de la función Directory.GetFiles() ) de un buscador de archivos y directorios, aunque solo he dejado visible dos métodos en el código fuente para que puedas buscar archivos.

Aparte de los grandes beneficios en velocidad que podrás comprobar por ti miso en los tests aquí abajo del todo de este comentario, este buscador también soporta la característica de buscar por múltiples patrones de nombre y por múltiples patrones de extensiones al mismo tiempo, así como la capacidad de poder excluir sin miedo algunos cualquier directorio en el que el usuario no disponga de permisos de lectura (con la posibilidad adicional de lanzar una excepción de acceso no autorizado si así se desea hacer), cosa que con las funciones built-in de .NET Framework no se puede controlar de forma natural.

Simplemente copiar y pegar. Aquí tienes:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 14-November-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Option Statements "
  7.  
  8. Option Strict On
  9. Option Explicit On
  10. Option Infer Off
  11.  
  12. #End Region
  13.  
  14. #Region " Imports "
  15.  
  16. Imports System.Collections.Concurrent
  17. Imports System.IO
  18. Imports System.Linq
  19. Imports System.Security
  20. Imports System.Threading.Tasks
  21.  
  22. #End Region
  23.  
  24. #Region " ElektroKit.Core.IO.Tools.Files "
  25.  
  26. Namespace ElektroKit.Core.IO.Tools
  27.  
  28.    ''' ----------------------------------------------------------------------------------------------------
  29.    ''' <summary>
  30.    ''' Contains file related utilities.
  31.    ''' </summary>
  32.    ''' ----------------------------------------------------------------------------------------------------
  33.    Public NotInheritable Class Files
  34.  
  35. #Region " Constructors "
  36.  
  37.        ''' ----------------------------------------------------------------------------------------------------
  38.        ''' <summary>
  39.        ''' Prevents a default instance of the <see cref="Files"/> class from being created.
  40.        ''' </summary>
  41.        ''' ----------------------------------------------------------------------------------------------------
  42.        <DebuggerNonUserCode>
  43.        Private Sub New()
  44.        End Sub
  45.  
  46. #End Region
  47.  
  48. #Region " Public Methods "
  49.  
  50.        ''' ----------------------------------------------------------------------------------------------------
  51.        ''' <summary>
  52.        ''' Gets the files those matches the criteria inside the specified directory and/or sub-directories.
  53.        ''' </summary>
  54.        ''' ----------------------------------------------------------------------------------------------------
  55.        ''' <param name="dirPath">
  56.        ''' The root directory path to search for files.
  57.        ''' </param>
  58.        '''
  59.        ''' <param name="searchOption">
  60.        ''' The searching mode.
  61.        ''' </param>
  62.        '''
  63.        ''' <param name="fileNamePatterns">
  64.        ''' The file name pattern(s) to match.
  65.        ''' </param>
  66.        '''
  67.        ''' <param name="fileExtPatterns">
  68.        ''' The file extension pattern(s) to match.
  69.        ''' </param>
  70.        '''
  71.        ''' <param name="ignoreCase">
  72.        ''' If <see langword="True"/>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.
  73.        ''' </param>
  74.        '''
  75.        ''' <param name="throwOnError">
  76.        ''' If set to <see langword="True"/>, exceptions will be thrown, like access denied to file or directory.
  77.        ''' </param>
  78.        ''' ----------------------------------------------------------------------------------------------------
  79.        ''' <returns>
  80.        ''' An <see cref="IEnumerable(Of FileInfo)"/> instance containing the files information.
  81.        ''' </returns>
  82.        ''' ----------------------------------------------------------------------------------------------------
  83.        ''' <exception cref="ArgumentException">dirPath or searchOption
  84.        ''' </exception>
  85.        ''' ----------------------------------------------------------------------------------------------------
  86.        <DebuggerStepThrough>
  87.        Friend Shared Function GetFiles(ByVal dirPath As String,
  88.                                        ByVal searchOption As SearchOption,
  89.                                        Optional ByVal fileNamePatterns As String() = Nothing,
  90.                                        Optional ByVal fileExtPatterns As String() = Nothing,
  91.                                        Optional ByVal ignoreCase As Boolean = True,
  92.                                        Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of FileInfo)
  93.  
  94.            ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  95.            Files.AnalyzePath(dirPath)
  96.  
  97.            ' Analyze the passed arguments.
  98.            Files.AnalyzeArgs(dirPath, searchOption)
  99.  
  100.            ' Get and return the files.
  101.            Dim queue As New ConcurrentQueue(Of FileInfo)
  102.            Files.CollectFiles(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  103.            Return queue.AsEnumerable
  104.  
  105.        End Function
  106.  
  107.        ''' ----------------------------------------------------------------------------------------------------
  108.        ''' <summary>
  109.        ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  110.        ''' </summary>
  111.        ''' ----------------------------------------------------------------------------------------------------
  112.        ''' <param name="dirPath">
  113.        ''' The root directory path to search for files.
  114.        ''' </param>
  115.        '''
  116.        ''' <param name="searchOption">
  117.        ''' The searching mode.
  118.        ''' </param>
  119.        '''
  120.        ''' <param name="fileNamePatterns">
  121.        ''' The file name pattern(s) to match.
  122.        ''' </param>
  123.        '''
  124.        ''' <param name="fileExtPatterns">
  125.        ''' The file extension pattern(s) to match.
  126.        ''' </param>
  127.        '''
  128.        ''' <param name="ignoreCase">
  129.        ''' If <see langword="True"/>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.
  130.        ''' </param>
  131.        '''
  132.        ''' <param name="throwOnError">
  133.        ''' If set to <see langword="True"/>, exceptions will be thrown, like access denied to file or directory.
  134.        ''' </param>
  135.        ''' ----------------------------------------------------------------------------------------------------
  136.        ''' <returns>
  137.        ''' An <see cref="IEnumerable(Of String)"/> instance containing the filepaths.
  138.        ''' </returns>
  139.        ''' ----------------------------------------------------------------------------------------------------
  140.        ''' <exception cref="ArgumentException">dirPath or searchOption
  141.        ''' </exception>
  142.        ''' ----------------------------------------------------------------------------------------------------
  143.        <DebuggerStepThrough>
  144.        Friend Shared Function GetFilePaths(ByVal dirPath As String,
  145.                                            ByVal searchOption As SearchOption,
  146.                                            Optional ByVal fileNamePatterns As String() = Nothing,
  147.                                            Optional ByVal fileExtPatterns As String() = Nothing,
  148.                                            Optional ByVal ignoreCase As Boolean = True,
  149.                                            Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  150.  
  151.            ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  152.            Files.AnalyzePath(dirPath)
  153.  
  154.            ' Analyze the passed arguments.
  155.            Files.AnalyzeArgs(dirPath, searchOption)
  156.  
  157.            ' Get and return the filepaths.
  158.            Dim queue As New ConcurrentQueue(Of String)
  159.            Files.CollectFilePaths(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  160.            Return queue.AsEnumerable
  161.  
  162.        End Function
  163.  
  164. #End Region
  165.  
  166. #Region " Private Methods "
  167.  
  168.        ''' ----------------------------------------------------------------------------------------------------
  169.        ''' <summary>
  170.        ''' Analyzes a directory path and perform specific changes on it.
  171.        ''' </summary>
  172.        ''' ----------------------------------------------------------------------------------------------------
  173.        ''' <param name="refDirPath">
  174.        ''' The directory path.
  175.        ''' </param>
  176.        ''' ----------------------------------------------------------------------------------------------------
  177.        ''' <exception cref="ArgumentNullException">dirPath;Value is null, empty, or white-spaced.
  178.        ''' </exception>
  179.        ''' ----------------------------------------------------------------------------------------------------
  180.        <DebuggerStepThrough>
  181.        Private Shared Sub AnalyzePath(ByRef refDirPath As String)
  182.  
  183.            If String.IsNullOrEmpty(refDirPath) OrElse String.IsNullOrWhiteSpace(refDirPath) Then
  184.                Throw New ArgumentNullException("dirPath", "Value is null, empty, or white-spaced.")
  185.  
  186.            Else
  187.                ' Trim unwanted characters.
  188.                refDirPath = refDirPath.TrimStart({" "c}).TrimEnd({" "c})
  189.  
  190.                If Path.IsPathRooted(refDirPath) Then
  191.                    ' The root paths contained on the returned FileInfo objects will start with the same string-case as this root path.
  192.                    ' So just for a little visual improvement, I'll treat this root path as a Drive-Letter and I convert it to UpperCase.
  193.                    refDirPath = Char.ToUpper(refDirPath.First()) & refDirPath.Substring(1)
  194.                End If
  195.  
  196.                If Not refDirPath.EndsWith("\"c) Then
  197.                    ' Possibly its a drive letter without backslash ('C:') or else just a normal path without backslash ('C\Dir').
  198.                    ' In any case, fix the ending backslash.
  199.                    refDirPath = refDirPath.Insert(refDirPath.Length, "\"c)
  200.                End If
  201.  
  202.            End If
  203.  
  204.        End Sub
  205.  
  206.        ''' ----------------------------------------------------------------------------------------------------
  207.        ''' <summary>
  208.        ''' Analyzes the specified directory values.
  209.        ''' </summary>
  210.        ''' ----------------------------------------------------------------------------------------------------
  211.        ''' <param name="dirPath">
  212.        ''' The root directory path to search for files.
  213.        ''' </param>
  214.        '''
  215.        ''' <param name="searchOption">
  216.        ''' The searching mode.
  217.        ''' </param>
  218.        ''' ----------------------------------------------------------------------------------------------------
  219.        ''' <exception cref="ArgumentException">dirPath or searchOption
  220.        ''' </exception>
  221.        ''' ----------------------------------------------------------------------------------------------------
  222.        <DebuggerStepThrough>
  223.        Private Shared Sub AnalyzeArgs(ByVal dirPath As String, ByVal searchOption As SearchOption)
  224.  
  225.            If Not Directory.Exists(dirPath) Then
  226.                Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  227.  
  228.            ElseIf (searchOption <> SearchOption.TopDirectoryOnly) AndAlso (searchOption <> SearchOption.AllDirectories) Then
  229.                Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  230.  
  231.            End If
  232.  
  233.        End Sub
  234.  
  235.        ''' ----------------------------------------------------------------------------------------------------
  236.        ''' <summary>
  237.        ''' Tries to instance the by-reference <see cref="DirectoryInfo"/> object using the given directory path.
  238.        ''' </summary>
  239.        ''' ----------------------------------------------------------------------------------------------------
  240.        ''' <param name="dirPath">
  241.        ''' The directory path used to instance the by-reference <see cref="DirectoryInfo"/> object.
  242.        ''' </param>
  243.        '''
  244.        ''' <param name="refDirInfo">
  245.        ''' The by-reference <see cref="DirectoryInfo"/> object to instance it using the given directory path.
  246.        ''' </param>
  247.        '''
  248.        ''' <param name="throwOnError">
  249.        ''' If set to <see langword="True"/>, exceptions will be thrown, like access denied to directory.
  250.        ''' </param>
  251.        ''' ----------------------------------------------------------------------------------------------------
  252.        <DebuggerStepThrough>
  253.        Private Shared Sub SetupDirInfoObject(ByVal dirPath As String,
  254.                                              ByRef refDirInfo As DirectoryInfo,
  255.                                              ByVal throwOnError As Boolean)
  256.  
  257.            Try
  258.                refDirInfo = New DirectoryInfo(dirPath)
  259.  
  260.            Catch ex As Exception
  261.  
  262.                Select Case ex.GetType ' Handle or suppress exceptions by its type,
  263.  
  264.                    ' I've wrote different types just to feel free to extend this feature in the future.
  265.                    Case GetType(ArgumentNullException),
  266.                         GetType(ArgumentException),
  267.                         GetType(SecurityException),
  268.                         GetType(PathTooLongException),
  269.                         ex.GetType
  270.  
  271.                        If throwOnError Then
  272.                            Throw
  273.                        End If
  274.  
  275.                End Select
  276.  
  277.            End Try
  278.  
  279.        End Sub
  280.  
  281.        ''' ----------------------------------------------------------------------------------------------------
  282.        ''' <summary>
  283.        ''' Tries to instance the by-reference <paramref name="refCol"/> object using the given directory path.
  284.        ''' </summary>
  285.        ''' ----------------------------------------------------------------------------------------------------
  286.        ''' <typeparam name="A">
  287.        ''' The type of the <paramref name="refCol"/> object used to cast and fill the by-reference collection.
  288.        ''' </typeparam>
  289.        '''
  290.        ''' <param name="objectAction">
  291.        ''' The method to invoke, only for <see cref="FileInfo"/> or <see cref="DirectoryInfo"/> objects, this parameter can be <see langword="Nothing"/>.
  292.        ''' </param>
  293.        '''
  294.        ''' <param name="sharedAction">
  295.        ''' The method to invoke, only for filepaths or directorypaths, this parameter can be <see langword="Nothing"/>.
  296.        ''' </param>
  297.        '''
  298.        ''' <param name="dirPath">
  299.        ''' The directory path used to instance the by-reference <paramref name="refCol"/> object.
  300.        ''' </param>
  301.        '''
  302.        ''' <param name="searchPattern">
  303.        ''' The search pattern to list files or directories.
  304.        ''' </param>
  305.        '''
  306.        ''' <param name="refCol">
  307.        ''' The by-reference <see cref="IEnumerable(Of A)"/> object to instance it using the given directory path.
  308.        ''' </param>
  309.        '''
  310.        ''' <param name="throwOnError">
  311.        ''' If set to <see langword="True"/>, exceptions will be thrown, like access denied to file or directory.
  312.        ''' </param>
  313.        ''' ----------------------------------------------------------------------------------------------------
  314.        <DebuggerStepThrough>
  315.        Private Shared Sub SetupFileDirCollection(Of A)(ByVal objectAction As Func(Of String, SearchOption,
  316.                                                                                              IEnumerable(Of A)),
  317.                                                    ByVal sharedAction As Func(Of String, String,
  318.                                                                                          SearchOption,
  319.                                                                                          IEnumerable(Of A)),
  320.                                                    ByVal dirPath As String,
  321.                                                    ByVal searchPattern As String,
  322.                                                    ByRef refCol As IEnumerable(Of A),
  323.                                                    ByVal throwOnError As Boolean)
  324.  
  325.            Try
  326.                If objectAction IsNot Nothing Then
  327.                    refCol = objectAction.Invoke(searchPattern, SearchOption.TopDirectoryOnly)
  328.  
  329.                ElseIf sharedAction IsNot Nothing Then
  330.                    refCol = sharedAction.Invoke(dirPath, searchPattern, SearchOption.TopDirectoryOnly)
  331.  
  332.                Else
  333.                    Throw New ArgumentException("Any Action has been defined.")
  334.  
  335.                End If
  336.  
  337.            Catch ex As Exception
  338.  
  339.                Select Case ex.GetType ' Handle or suppress exceptions by its type,
  340.  
  341.                    ' I've wrote different types just to feel free to extend this feature in the future.
  342.                    Case GetType(UnauthorizedAccessException),
  343.                         GetType(DirectoryNotFoundException),
  344.                         ex.GetType
  345.  
  346.                        If throwOnError Then
  347.                            Throw
  348.                        End If
  349.  
  350.                End Select
  351.  
  352.            End Try
  353.  
  354.        End Sub
  355.  
  356.        ''' ----------------------------------------------------------------------------------------------------
  357.        ''' <summary>
  358.        ''' Determines whether at least one of the specified patterns matches the given value.
  359.        ''' </summary>
  360.        ''' ----------------------------------------------------------------------------------------------------
  361.        ''' <param name="value">
  362.        ''' The value, which can be a filename, file extension, direcrory path, or directory name.
  363.        ''' </param>
  364.        '''
  365.        ''' <param name="patterns">
  366.        ''' The patterns to match the given value.
  367.        ''' </param>
  368.        '''
  369.        ''' <param name="ignoreCase">
  370.        ''' If set to <see langword="True"/>, compares ignoring string-case rules.
  371.        ''' </param>
  372.        ''' ----------------------------------------------------------------------------------------------------
  373.        ''' <returns>
  374.        ''' <see langword="True"/> at least one of the specified patterns matches the given value; <see langword="False"/> otherwise.
  375.        ''' </returns>
  376.        ''' ----------------------------------------------------------------------------------------------------
  377.        <DebuggerStepThrough>
  378.        Private Shared Function IsMatchPattern(ByVal value As String,
  379.                                               ByVal patterns As IEnumerable(Of String),
  380.                                               ByVal ignoreCase As Boolean) As Boolean
  381.  
  382.            ' Iterate the filename pattern(s) to match each name pattern on the current name.
  383.            For Each pattern As String In patterns
  384.  
  385.                ' Supress consecuent conditionals if pattern its an asterisk.
  386.                If pattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  387.                    Return True
  388.  
  389.                ElseIf ignoreCase Then ' Compare name ignoring string-case rules.
  390.                    If value.ToLower Like pattern.ToLower Then
  391.                        Return True
  392.                    End If
  393.  
  394.                Else ' Compare filename unignoring string-case rules.
  395.                    If value Like pattern Then
  396.                        Return True
  397.                    End If
  398.  
  399.                End If ' ignoreCase
  400.  
  401.            Next pattern
  402.  
  403.            Return False
  404.  
  405.        End Function
  406.  
  407.        ''' <summary>
  408.        ''' Runs the next collector tasks synchronouslly.
  409.        ''' </summary>
  410.        <DebuggerStepThrough>
  411.        Private Shared Sub RunNextTasks(Of T)(ByVal action As Action(Of ConcurrentQueue(Of T),
  412.                                                                     String,
  413.                                                                     SearchOption,
  414.                                                                     IEnumerable(Of String),
  415.                                                                     IEnumerable(Of String),
  416.                                                                     Boolean,
  417.                                                                     Boolean),
  418.                                              ByVal queue As ConcurrentQueue(Of T),
  419.                                              ByVal dirPath As String,
  420.                                              ByVal firstPatterns As IEnumerable(Of String),
  421.                                              ByVal secondPatterns As IEnumerable(Of String),
  422.                                              ByVal ignoreCase As Boolean,
  423.                                              ByVal throwOnError As Boolean)
  424.  
  425.            Try
  426.                Task.WaitAll(New DirectoryInfo(dirPath).
  427.                                 GetDirectories.
  428.                                 Select(Function(dir As DirectoryInfo)
  429.                                            Return Task.Factory.StartNew(Sub()
  430.                                                                             action.Invoke(queue,
  431.                                                                                           dir.FullName, SearchOption.AllDirectories,
  432.                                                                                           firstPatterns, secondPatterns,
  433.                                                                                           ignoreCase, throwOnError)
  434.                                                                         End Sub)
  435.                                        End Function).ToArray)
  436.  
  437.            Catch ex As Exception
  438.  
  439.                Select Case ex.GetType ' Handle or suppress exceptions by its type,
  440.  
  441.                    ' I've wrote different types just to feel free to extend this feature in the future.
  442.                    Case GetType(UnauthorizedAccessException),
  443.                         GetType(DirectoryNotFoundException),
  444.                         ex.GetType
  445.  
  446.                        If throwOnError Then
  447.                            Throw
  448.                        End If
  449.  
  450.                End Select
  451.  
  452.            End Try
  453.  
  454.        End Sub
  455.  
  456.        ''' <summary>
  457.        ''' Collects the files those matches the criteria inside the specified directory and/or sub-directories.
  458.        ''' </summary>
  459.        <DebuggerStepThrough>
  460.        Private Shared Sub CollectFiles(ByVal queue As ConcurrentQueue(Of FileInfo),
  461.                                        ByVal dirPath As String,
  462.                                        ByVal searchOption As SearchOption,
  463.                                        ByVal fileNamePatterns As IEnumerable(Of String),
  464.                                        ByVal fileExtPatterns As IEnumerable(Of String),
  465.                                        ByVal ignoreCase As Boolean,
  466.                                        ByVal throwOnError As Boolean)
  467.  
  468.            ' Initialize a FileInfo collection.
  469.            Dim fileInfoCol As IEnumerable(Of FileInfo) = Nothing
  470.  
  471.            ' Initialize a DirectoryInfo.
  472.            Dim dirInfo As DirectoryInfo = Nothing
  473.            SetupDirInfoObject(dirPath, dirInfo, throwOnError)
  474.  
  475.            If fileExtPatterns IsNot Nothing Then
  476.                ' Decrease time execution by searching for files that has extension.
  477.                SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  478.                                                    dirInfo.FullName, "*.*", fileInfoCol, throwOnError)
  479.            Else
  480.                ' Search for all files.
  481.                SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  482.                                                    dirInfo.FullName, "*", fileInfoCol, throwOnError)
  483.            End If
  484.  
  485.            ' If the fileInfoCol collection is not empty then...
  486.            If fileInfoCol IsNot Nothing Then
  487.  
  488.                ' Iterate the files.
  489.                For Each fInfo As FileInfo In fileInfoCol
  490.  
  491.                    ' Flag to determine whether a filename pattern is matched. Activated by default.
  492.                    Dim flagNamePattern As Boolean = True
  493.  
  494.                    ' Flag to determine whether a file extension pattern is matched. Activated by default.
  495.                    Dim flagExtPattern As Boolean = True
  496.  
  497.                    ' If filename patterns collection is not empty then...
  498.                    If fileNamePatterns IsNot Nothing Then
  499.                        flagNamePattern = IsMatchPattern(fInfo.Name, fileNamePatterns, ignoreCase)
  500.                    End If
  501.  
  502.                    ' If file extension patterns collection is not empty then...
  503.                    If fileExtPatterns IsNot Nothing Then
  504.                        flagExtPattern = IsMatchPattern(fInfo.Extension, fileExtPatterns, ignoreCase)
  505.                    End If
  506.  
  507.                    ' If fileName and also fileExtension patterns are matched then...
  508.                    If flagNamePattern AndAlso flagExtPattern Then
  509.                        queue.Enqueue(fInfo) ' Enqueue this FileInfo object.
  510.                    End If
  511.  
  512.                Next fInfo
  513.  
  514.            End If ' fileInfoCol IsNot Nothing
  515.  
  516.            ' If searchOption is recursive then...
  517.            If searchOption = SearchOption.AllDirectories Then
  518.                RunNextTasks(Of FileInfo)(AddressOf CollectFiles,
  519.                                          queue, dirInfo.FullName, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  520.            End If
  521.  
  522.        End Sub
  523.  
  524.        ''' <summary>
  525.        ''' Collects the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  526.        ''' </summary>
  527.        <DebuggerStepThrough>
  528.        Private Shared Sub CollectFilePaths(ByVal queue As ConcurrentQueue(Of String),
  529.                                            ByVal dirPath As String,
  530.                                            ByVal searchOption As SearchOption,
  531.                                            ByVal fileNamePatterns As IEnumerable(Of String),
  532.                                            ByVal fileExtPatterns As IEnumerable(Of String),
  533.                                            ByVal ignoreCase As Boolean,
  534.                                            ByVal throwOnError As Boolean)
  535.  
  536.            ' Initialize a filepath collection.
  537.            Dim filePathCol As IEnumerable(Of String) = Nothing
  538.  
  539.            If fileExtPatterns IsNot Nothing Then
  540.                ' Decrease time execution by searching for files that has extension.
  541.                SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  542.                                                  dirPath, "*.*", filePathCol, throwOnError)
  543.            Else
  544.                ' Search for all files.
  545.                SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  546.                                                  dirPath, "*", filePathCol, throwOnError)
  547.            End If
  548.  
  549.            ' If the filepath collection is not empty then...
  550.            If filePathCol IsNot Nothing Then
  551.  
  552.                ' Iterate the filepaths.
  553.                For Each filePath As String In filePathCol
  554.  
  555.                    ' Flag to determine whether a filename pattern is matched. Activated by default.
  556.                    Dim flagNamePattern As Boolean = True
  557.  
  558.                    ' Flag to determine whether a file extension pattern is matched. Activated by default.
  559.                    Dim flagExtPattern As Boolean = True
  560.  
  561.                    ' If filename patterns collection is not empty then...
  562.                    If fileNamePatterns IsNot Nothing Then
  563.                        flagNamePattern = IsMatchPattern(Path.GetFileNameWithoutExtension(filePath), fileNamePatterns, ignoreCase)
  564.                    End If
  565.  
  566.                    ' If file extension patterns collection is not empty then...
  567.                    If fileExtPatterns IsNot Nothing Then
  568.                        flagExtPattern = IsMatchPattern(Path.GetExtension(filePath), fileExtPatterns, ignoreCase)
  569.                    End If
  570.  
  571.                    ' If fileName and also fileExtension patterns are matched then...
  572.                    If flagNamePattern AndAlso flagExtPattern Then
  573.                        queue.Enqueue(filePath) ' Enqueue this filepath.
  574.                    End If
  575.  
  576.                Next filePath
  577.  
  578.            End If ' filePathCol IsNot Nothing
  579.  
  580.            ' If searchOption is recursive then...
  581.            If searchOption = SearchOption.AllDirectories Then
  582.                RunNextTasks(Of String)(AddressOf CollectFilePaths,
  583.                                        queue, dirPath, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  584.            End If
  585.  
  586.        End Sub
  587.  
  588. #End Region
  589.  
  590.    End Class
  591.  
  592. End Namespace
  593.  
  594. #End Region
  595.  



Puedes testear la velocidad de mi función y compararlo con las funciones Directory.GetFiles() y My.Computer.FileSystem.GetFiles() mediante el siguiente código:

Código
  1. Imports System.Collections.ObjectModel
  2. Imports System.IO
  3.  
  4. Module Module1
  5.  
  6.    Sub Main()
  7.  
  8.        Dim dirPath As String = "C:\"
  9.  
  10.        Dim methodDirectoryGetFiles As String()
  11.        Dim methodMyComputerGetFiles As ReadOnlyCollection(Of String)
  12.        Dim methodElektroGetFiles As IEnumerable(Of String)
  13.        Dim sw As New Stopwatch()
  14.  
  15.        sw.Start()
  16.        methodDirectoryGetFiles = Directory.GetFiles(dirPath, "*", IO.SearchOption.AllDirectories)
  17.        sw.Stop()
  18.        Debug.WriteLine(String.Format("method DirectoryGetFiles  - Elapsed Time: {0}", sw.Elapsed.ToString("mm\:ss\:ffff")))
  19.  
  20.        sw.Reset()
  21.        sw.Start()
  22.        methodMyComputerGetFiles = My.Computer.FileSystem.GetFiles(dirPath, FileIO.SearchOption.SearchAllSubDirectories, "*")
  23.        sw.Stop()
  24.        Debug.WriteLine(String.Format("method MyComputerGetFiles - Elapsed Time: {0}", sw.Elapsed.ToString("mm\:ss\:ffff")))
  25.  
  26.        sw.Reset()
  27.        sw.Start()
  28.        methodElektroGetFiles = ElektroKit.Core.IO.Tools.Files.GetFilePaths(dirPath, IO.SearchOption.AllDirectories, Nothing, {"*"}, True, True)
  29.        sw.Stop()
  30.        Debug.WriteLine(String.Format("method ElektroGetFiles    - Elapsed Time: {0}", sw.Elapsed.ToString("mm\:ss\:ffff")))
  31.  
  32.    End Sub
  33.  
  34. End Module

Aquí tienes unos tests que he realizado:

Código:
Directorio: P:\
Patrón de búsqueda: "*"
Búsqueda recursiva: Sí
Cantidad de archivos a analizar: 142.880 y 7.374 carpetas
Tamaño total de los archivos: 238 Gigabytes
Tamaño por Colección/Array: 142.880 elementos
------------------------------------------------------------
method DirectoryGetFiles  - Elapsed Time: 00:01:4564 ++
method MyComputerGetFiles - Elapsed Time: 02:59:5497 +++
method ElektroGetFiles    - Elapsed Time: 00:00:5751 +

Código:
Directorio: G:\
Patrón de búsqueda: "*"
Búsqueda recursiva: Sí
Cantidad de archivos a analizar: 373.384 y 28.721 carpetas
Tamaño total de los archivos: 1.58 Terabytes
Tamaño por Colección/Array: 373.384 elementos
------------------------------------------------------------
method DirectoryGetFiles  - Elapsed Time: 00:04:5291 ++
method MyComputerGetFiles - Elapsed Time: 24:00:5846 +++ (si, eso han sido 24 ***** minutos los que ha tardado)
method ElektroGetFiles    - Elapsed Time: 00:01:7399 +

Código:
Directorio: C:\Windows\System32
Patrón de búsqueda: "*.dll"
Búsqueda recursiva: No
Cantidad de archivos a analizar: 3.465
Tamaño de archivos: 1.60 Gigabytes
Tamaño por Colección/Array: 2.620 elementos
------------------------------------------------------------
method DirectoryGetFiles  - Elapsed Time: 00:00:0138 +
method MyComputerGetFiles - Elapsed Time: 00:00:0608 +++
method ElektroGetFiles    - Elapsed Time: 00:00:0151 ++

Como puedes comprobar, mi implementación es altamente velóz cuanto mayor es la cantidad de archivos a analizar, y es casi igual de eficiente a la función Directory.GetFiles() cuando se trata de una cantidad pequeña de archivos a analizar, con una diferencia ínfima de milisegundos... lo que hace que merezca mucho la pena usarlo si necesitamos buscar varias extensiones de archivo al mismo tiempo.

Bueno, y de la función My.Computer.FileSystem.GetFiles mejor ni hablemos, los resultados hablan por si mismos. Los miembros expuestos en  "My.Computer" al igual que en Microsoft.VisualBasic están muy poco optimizados y ningún programador de VB.NET al que le preocupe el rendimiento de su app debería usarlos. De hecho en el foro he repetido mil veces que los miembros del namespace Microsoft.VisualBasic solo existen por temas de compatibilidad y conformidad por gente que migre de VB6 a VB.NET y lo tengan más facil para orientarse, que ningún programador de VB.NET debería utilizar el namespace Microsoft.VisualBasic más que para mostrar un MsgBox y listo xD, se creerán que hablo por hablar o algo... pues bueno, pueden ver por ustedes mismos el nefasto código fuente en la referencia online del source de .NET Framework.

PD: Estos tests se han realizado bajo circunstancias óptimas, realizando dos veces consecutivas cada llamada a cada uno de los tres métodos para que la caché de archivos enumerados del disco se actualizase y evitar así diferencias dispares en el tiempo de ejecución entre cada método.

Un saludo.


« Última modificación: 23 Septiembre 2017, 12:58 pm por Eleкtro » En línea

**Aincrad**


Desconectado Desconectado

Mensajes: 668



Ver Perfil WWW
Re: ayuda con manejo de archivos en vb.net 2008
« Respuesta #11 en: 23 Septiembre 2017, 01:08 am »

  :o  :o  :o  :o . mierrrrrrrr.      todo eso  lo creaste tu  :o ,   la verdad me has dejado
 impresionado .  creo que yo nunca podría hacer algo así. 

gracias de verdad por el code trabaja bien y es rápido. estoy en sorprendido.   :o .

                               Gracias Elektro me fue de gran ayuda.



En línea



Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: ayuda con manejo de archivos en vb.net 2008
« Respuesta #12 en: 23 Septiembre 2017, 13:08 pm »

 :o  :o  :o  :o . mierrrrrrrr.      todo eso  lo creaste tu  :o ,   la verdad me has dejado
 impresionado .  creo que yo nunca podría hacer algo así.  

Gracias, pero ese código no se merece mucha admiración, es viejito... le faltan varias revisiones de refactorización para tratar de optimizarlo más.

Me alegro de que te haya servido.

Saludos
« Última modificación: 23 Septiembre 2017, 13:11 pm por Eleкtro » En línea

Páginas: 1 [2] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Ayuda en manejo de Archivos en Lenguaje C
Programación C/C++
theluigy13etv 3 3,540 Último mensaje 9 Diciembre 2011, 01:28 am
por rir3760
Ayuda para el manejo de archivos[Solucuionado]
.NET (C#, VB.NET, ASP)
Sk9ITk5Z 3 3,425 Último mensaje 31 Enero 2012, 17:27 pm
por Sk9ITk5Z
ayuda con manejo de archivos en c
Programación C/C++
tamyta_19 4 2,660 Último mensaje 24 Abril 2015, 17:03 pm
por tamyta_19
Ayuda con MANEJO DE ARCHIVOS
Programación C/C++
felixgz 1 1,747 Último mensaje 2 Marzo 2016, 23:36 pm
por carolabeatle
Ayuda con Manejo de archivos!
Programación C/C++
pedro0620 1 1,988 Último mensaje 9 Septiembre 2016, 16:02 pm
por AlbertoBSD
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines