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

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


  Mostrar Mensajes
Páginas: 1 ... 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 [580] 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 ... 1236
5791  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 14 Febrero 2015, 20:30 pm
Esto es una versión "reducida" de la class para buscar archivos/directorios. El funcionamiento es el mismo pero internamente trabaja de manera ligeramente distinta, simplemente lo he estructurado de otra forma más óptima para eliminar toda la repetición de código posible y así hacer el entendimiento del código más ameno, los resultados son los mismos.

Nota: Si alquien quiere comparar este código con algún otro algoritmo (que de seguro los hay mejores) para hacer algún tipo de profilling de I/O o del rendimiento de memoria entonces no se vayan a asustar por el consumo de memoria al recojer +100k de archivos, es el GarbageCollector de .Net haciendo de las suyas... lo pueden invokar manualmente (GC.Collect) y desaparecerá todo ese consumo ficticio de RAM.

Espero que a alguien le sirva el code :):

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 14-February-2015
  4. ' ***********************************************************************
  5.  
  6. #Region " Usage Examples "
  7.  
  8. ' he eliminado esto por el límite de caracteres del foro
  9.  
  10. #End Region
  11.  
  12. #Region " Option Statements "
  13.  
  14. Option Explicit On
  15. Option Strict On
  16. Option Infer Off
  17.  
  18. #End Region
  19.  
  20. #Region " Imports "
  21.  
  22. Imports System.IO
  23. Imports System.Collections.Concurrent
  24. Imports System.Threading.Tasks
  25.  
  26. #End Region
  27.  
  28. #Region " File Dir Searcher "
  29.  
  30. ''' <summary>
  31. ''' Searchs for files and directories.
  32. ''' </summary>
  33. Public NotInheritable Class FileDirSearcher
  34.  
  35. #Region " Public Methods "
  36.  
  37.    ''' <summary>
  38.    ''' Gets the files those matches the criteria inside the specified directory and/or sub-directories.
  39.    ''' </summary>
  40.    ''' <param name="dirPath">The root directory path to search for files.</param>
  41.    ''' <param name="searchOption">The searching mode.</param>
  42.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  43.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  44.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  45.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  46.    ''' <returns>An <see cref="IEnumerable(Of FileInfo)"/> instance containing the files information.</returns>
  47.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  48.    Public Shared Function GetFiles(ByVal dirPath As String,
  49.                                    ByVal searchOption As SearchOption,
  50.                                    Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  51.                                    Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  52.                                    Optional ByVal ignoreCase As Boolean = True,
  53.                                    Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of FileInfo)
  54.  
  55.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  56.        AnalyzePath(dirPath)
  57.  
  58.        ' Analyze the passed arguments.
  59.        AnalyzeArgs(dirPath, searchOption)
  60.  
  61.        ' Get and return the files.
  62.        Dim queue As New ConcurrentQueue(Of FileInfo)
  63.        CollectFiles(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  64.        Return queue.AsEnumerable
  65.  
  66.    End Function
  67.  
  68.    ''' <summary>
  69.    ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  70.    ''' </summary>
  71.    ''' <param name="dirPath">The root directory path to search for files.</param>
  72.    ''' <param name="searchOption">The searching mode.</param>
  73.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  74.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  75.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  76.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  77.    ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the filepaths.</returns>
  78.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  79.    Public Shared Function GetFilePaths(ByVal dirPath As String,
  80.                                        ByVal searchOption As SearchOption,
  81.                                        Optional ByVal fileNamePatterns As IEnumerable(Of String) = Nothing,
  82.                                        Optional ByVal fileExtPatterns As IEnumerable(Of String) = Nothing,
  83.                                        Optional ByVal ignoreCase As Boolean = True,
  84.                                        Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  85.  
  86.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  87.        AnalyzePath(dirPath)
  88.  
  89.        ' Analyze the passed arguments.
  90.        AnalyzeArgs(dirPath, searchOption)
  91.  
  92.        ' Get and return the filepaths.
  93.        Dim queue As New ConcurrentQueue(Of String)
  94.        CollectFilePaths(queue, dirPath, searchOption, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  95.        Return queue.AsEnumerable
  96.  
  97.    End Function
  98.  
  99.    ''' <summary>
  100.    ''' Gets the directories those matches the criteria inside the specified directory and/or sub-directories.
  101.    ''' </summary>
  102.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  103.    ''' <param name="searchOption">The searching mode.</param>
  104.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  105.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  106.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  107.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  108.    ''' <returns>An <see cref="IEnumerable(Of DirectoryInfo)"/> instance containing the dirrectories information.</returns>
  109.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  110.    Public Shared Function GetDirs(ByVal dirPath As String,
  111.                                   ByVal searchOption As SearchOption,
  112.                                   Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  113.                                   Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  114.                                   Optional ByVal ignoreCase As Boolean = True,
  115.                                   Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of DirectoryInfo)
  116.  
  117.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  118.        AnalyzePath(dirPath)
  119.  
  120.        ' Analyze the passed arguments.
  121.        AnalyzeArgs(dirPath, searchOption)
  122.  
  123.        ' Get and return the directories.
  124.        Dim queue As New ConcurrentQueue(Of DirectoryInfo)
  125.        CollectDirs(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  126.        Return queue.AsEnumerable
  127.  
  128.    End Function
  129.  
  130.    ''' <summary>
  131.    ''' Gets the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  132.    ''' </summary>
  133.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  134.    ''' <param name="searchOption">The searching mode.</param>
  135.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  136.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  137.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  138.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  139.    ''' <returns>An <see cref="IEnumerable(Of String)"/> instance containing the directory paths.</returns>
  140.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  141.    Public Shared Function GetDirPaths(ByVal dirPath As String,
  142.                                       ByVal searchOption As SearchOption,
  143.                                       Optional ByVal dirPathPatterns As IEnumerable(Of String) = Nothing,
  144.                                       Optional ByVal dirNamePatterns As IEnumerable(Of String) = Nothing,
  145.                                       Optional ByVal ignoreCase As Boolean = True,
  146.                                       Optional ByVal throwOnError As Boolean = False) As IEnumerable(Of String)
  147.  
  148.        ' Analyze and resolve path problems. (eg. 'C:' -> 'C:\')
  149.        AnalyzePath(dirPath)
  150.  
  151.        ' Analyze the passed arguments.
  152.        AnalyzeArgs(dirPath, searchOption)
  153.  
  154.        ' Get and return the directory paths.
  155.        Dim queue As New ConcurrentQueue(Of String)
  156.        CollectDirPaths(queue, dirPath, searchOption, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  157.        Return queue.AsEnumerable
  158.  
  159.    End Function
  160.  
  161. #End Region
  162.  
  163. #Region " Private Methods "
  164.  
  165.    ''' <summary>
  166.    ''' Analyzes a directory path and perform specific changes on it.
  167.    ''' </summary>
  168.    ''' <param name="dirPath">The directory path.</param>
  169.    ''' <exception cref="System.ArgumentNullException">dirPath;Value is null, empty, or white-spaced.</exception>
  170.    Private Shared Sub AnalyzePath(ByRef dirPath As String)
  171.  
  172.        If String.IsNullOrEmpty(dirPath) OrElse String.IsNullOrWhiteSpace(dirPath) Then
  173.            Throw New ArgumentNullException("dirPath", "Value is null, empty, or white-spaced.")
  174.  
  175.        Else
  176.            ' Trim unwanted characters.
  177.            dirPath = dirPath.TrimStart({" "c}).TrimEnd({" "c})
  178.  
  179.            If Path.IsPathRooted(dirPath) Then
  180.                ' The root paths contained on the returned FileInfo objects will start with the same string-case as this root path.
  181.                ' So just for a little visual improvement, I'll treat this root path as a Drive-Letter and I convert it to UpperCase.
  182.                dirPath = Char.ToUpper(dirPath.First) & dirPath.Substring(1)
  183.            End If
  184.  
  185.            If Not dirPath.EndsWith("\"c) Then
  186.                ' Possibly its a drive letter without backslash ('C:') or else just a normal path without backslash ('C\Dir').
  187.                ' In any case, fix the ending backslash.
  188.                dirPath = dirPath.Insert(dirPath.Length, "\"c)
  189.            End If
  190.  
  191.        End If
  192.  
  193.    End Sub
  194.  
  195.    ''' <summary>
  196.    ''' Analyzes the specified directory values.
  197.    ''' </summary>
  198.    ''' <param name="dirPath">The root directory path to search for files.</param>
  199.    ''' <param name="searchOption">The searching mode.</param>
  200.    ''' <exception cref="System.ArgumentException">dirPath or searchOption</exception>
  201.    Private Shared Sub AnalyzeArgs(ByVal dirPath As String, ByVal searchOption As SearchOption)
  202.  
  203.        If Not Directory.Exists(dirPath) Then
  204.            Throw New ArgumentException(String.Format("Directory doesn't exists: '{0}'", dirPath), "dirPath")
  205.  
  206.        ElseIf (searchOption <> searchOption.TopDirectoryOnly) AndAlso (searchOption <> searchOption.AllDirectories) Then
  207.            Throw New ArgumentException(String.Format("Value of '{0}' is not valid enumeration value.", CStr(searchOption)), "searchOption")
  208.  
  209.        End If
  210.  
  211.    End Sub
  212.  
  213.    ''' <summary>
  214.    ''' Tries to instance the byreferred <see cref="DirectoryInfo"/> object using the given directory path.
  215.    ''' </summary>
  216.    ''' <param name="dirPath">The directory path used to instance the byreffered <see cref="DirectoryInfo"/> object.</param>
  217.    ''' <param name="dirInfo">The byreffered <see cref="DirectoryInfo"/> object to instance it using the given directory path.</param>
  218.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  219.    Private Shared Sub SetupDirInfoObject(ByVal dirPath As String,
  220.                                          ByRef dirInfo As DirectoryInfo,
  221.                                          ByVal throwOnError As Boolean)
  222.  
  223.        Try
  224.            dirInfo = New DirectoryInfo(dirPath)
  225.  
  226.        Catch ex As Exception
  227.  
  228.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  229.  
  230.                ' I've wrote different types just to feel free to expand this feature in the future.
  231.                Case GetType(ArgumentNullException),
  232.                     GetType(ArgumentException),
  233.                     GetType(Security.SecurityException),
  234.                     GetType(PathTooLongException),
  235.                     ex.GetType
  236.  
  237.                    If throwOnError Then
  238.                        Throw
  239.                    End If
  240.  
  241.            End Select
  242.  
  243.        End Try
  244.  
  245.    End Sub
  246.  
  247.    ''' <summary>
  248.    ''' Tries to instance the byreferred <paramref name="col"/> object using the given directory path.
  249.    ''' </summary>
  250.    ''' <typeparam name="A">The type of the <paramref name="col"/> object used to cast and fill the byreffered collection.</typeparam>
  251.    ''' <param name="objectAction">The method to invoke, only for <see cref="FileInfo"/> or <see cref="DirectoryInfo"/> objects, this parameter can be <c>Nothing</c>.</param>
  252.    ''' <param name="sharedAction">The method to invoke, only for filepaths or directorypaths, this parameter can be <c>Nothing</c>.</param>
  253.    ''' <param name="dirPath">The directory path used to instance the byreffered <paramref name="col"/> object.</param>
  254.    ''' <param name="searchPattern">The search pattern to list files or directories.</param>
  255.    ''' <param name="col">The byreffered <see cref="IEnumerable(Of A)"/> object to instance it using the given directory path.</param>
  256.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  257.    Private Shared Sub SetupFileDirCollection(Of A)(ByVal objectAction As Func(Of String,
  258.                                                                               SearchOption,
  259.                                                                               IEnumerable(Of A)),
  260.                                                    ByVal sharedAction As Func(Of String,
  261.                                                                             String,
  262.                                                                             SearchOption,
  263.                                                                             IEnumerable(Of A)),
  264.                                                    ByVal dirPath As String,
  265.                                                    ByVal searchPattern As String,
  266.                                                    ByRef col As IEnumerable(Of A),
  267.                                                    ByVal throwOnError As Boolean)
  268.  
  269.        Try
  270.            If objectAction IsNot Nothing Then
  271.                col = objectAction.Invoke(searchPattern, SearchOption.TopDirectoryOnly)
  272.  
  273.            ElseIf sharedAction IsNot Nothing Then
  274.                col = sharedAction.Invoke(dirPath, searchPattern, SearchOption.TopDirectoryOnly)
  275.  
  276.            Else
  277.                Throw New ArgumentException("Any Action has been defined.")
  278.  
  279.            End If
  280.  
  281.        Catch ex As Exception
  282.  
  283.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  284.  
  285.                ' I've wrote different types just to feel free to expand this feature in the future.
  286.                Case GetType(UnauthorizedAccessException),
  287.                     GetType(DirectoryNotFoundException),
  288.                     ex.GetType
  289.  
  290.                    If throwOnError Then
  291.                        Throw
  292.                    End If
  293.  
  294.            End Select
  295.  
  296.        End Try
  297.  
  298.    End Sub
  299.  
  300.    ''' <summary>
  301.    ''' Determines whether at least one of the specified patterns matches the given value.
  302.    ''' </summary>
  303.    ''' <param name="value">The value, which can be a filename, file extension, direcrory path, or directory name.</param>
  304.    ''' <param name="patterns">The patterns to match the given value.</param>
  305.    ''' <param name="ignoreCase">if set to <c>true</c>, compares ignoring string-case rules.</param>
  306.    ''' <returns><c>true</c> at least one of the specified patterns matches the given value; <c>false</c> otherwise.</returns>
  307.    Private Shared Function IsMatchPattern(ByVal value As String,
  308.                                           ByVal patterns As IEnumerable(Of String),
  309.                                           ByVal ignoreCase As Boolean) As Boolean
  310.  
  311.        ' Iterate the filename pattern(s) to match each name pattern on the current name.
  312.        For Each pattern As String In patterns
  313.  
  314.            ' Supress consecuent conditionals if pattern its an asterisk.
  315.            If pattern.Equals("*", StringComparison.OrdinalIgnoreCase) Then
  316.                Return True
  317.  
  318.            ElseIf ignoreCase Then ' Compare name ignoring string-case rules.
  319.                If value.ToLower Like pattern.ToLower Then
  320.                    Return True
  321.                End If
  322.  
  323.            Else ' Compare filename unignoring string-case rules.
  324.                If value Like pattern Then
  325.                    Return True
  326.                End If
  327.  
  328.            End If ' ignoreCase
  329.  
  330.        Next pattern
  331.  
  332.        Return False
  333.  
  334.    End Function
  335.  
  336.    ''' <summary>
  337.    ''' Runs the next collector tasks synchronouslly.
  338.    ''' </summary>
  339.    ''' <typeparam name="T"></typeparam>
  340.    ''' <param name="action">The collector method to invoke.</param>
  341.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of FileInfo)"/> instance.</param>
  342.    ''' <param name="dirPath">The directory path.</param>
  343.    ''' <param name="firstPatterns">The first comparison patterns.</param>
  344.    ''' <param name="secondPatterns">The second comparison patterns.</param>
  345.    ''' <param name="ignoreCase">if set to <c>true</c>, compares ignoring string-case rules.</param>
  346.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  347.    Private Shared Sub RunNextTasks(Of T)(ByVal action As Action(Of ConcurrentQueue(Of T),
  348.                                                                 String,
  349.                                                                 SearchOption,
  350.                                                                 IEnumerable(Of String),
  351.                                                                 IEnumerable(Of String),
  352.                                                                 Boolean,
  353.                                                                 Boolean),
  354.                                          ByVal queue As ConcurrentQueue(Of T),
  355.                                          ByVal dirPath As String,
  356.                                          ByVal firstPatterns As IEnumerable(Of String),
  357.                                          ByVal secondPatterns As IEnumerable(Of String),
  358.                                          ByVal ignoreCase As Boolean,
  359.                                          ByVal throwOnError As Boolean)
  360.  
  361.        Try
  362.            Task.WaitAll(New DirectoryInfo(dirPath).
  363.                             GetDirectories.
  364.                             Select(Function(dir As DirectoryInfo)
  365.                                        Return Task.Factory.StartNew(Sub()
  366.                                                                         action.Invoke(queue,
  367.                                                                                       dir.FullName, SearchOption.AllDirectories,
  368.                                                                                       firstPatterns, secondPatterns,
  369.                                                                                       ignoreCase, throwOnError)
  370.                                                                     End Sub)
  371.                                    End Function).ToArray)
  372.  
  373.        Catch ex As Exception
  374.  
  375.            Select Case ex.GetType ' Handle or suppress exceptions by its type,
  376.  
  377.                ' I've wrote different types just to feel free to expand this feature in the future.
  378.                Case GetType(UnauthorizedAccessException),
  379.                     GetType(DirectoryNotFoundException),
  380.                     ex.GetType
  381.  
  382.                    If throwOnError Then
  383.                        Throw
  384.                    End If
  385.  
  386.            End Select
  387.  
  388.        End Try
  389.  
  390.    End Sub
  391.  
  392.    ''' <summary>
  393.    ''' Collects the files those matches the criteria inside the specified directory and/or sub-directories.
  394.    ''' </summary>
  395.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of FileInfo)"/> instance to enqueue new files.</param>
  396.    ''' <param name="dirPath">The root directory path to search for files.</param>
  397.    ''' <param name="searchOption">The searching mode.</param>
  398.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  399.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  400.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  401.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  402.    Private Shared Sub CollectFiles(ByVal queue As ConcurrentQueue(Of FileInfo),
  403.                                    ByVal dirPath As String,
  404.                                    ByVal searchOption As SearchOption,
  405.                                    ByVal fileNamePatterns As IEnumerable(Of String),
  406.                                    ByVal fileExtPatterns As IEnumerable(Of String),
  407.                                    ByVal ignoreCase As Boolean,
  408.                                    ByVal throwOnError As Boolean)
  409.  
  410.        ' Initialize a FileInfo collection.
  411.        Dim fileInfoCol As IEnumerable(Of FileInfo) = Nothing
  412.  
  413.        ' Initialize a DirectoryInfo.
  414.        Dim dirInfo As DirectoryInfo = Nothing
  415.        SetupDirInfoObject(dirPath, dirInfo, throwOnError)
  416.  
  417.        If fileExtPatterns IsNot Nothing Then
  418.            ' Decrease time execution by searching for files that has extension.
  419.            SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  420.                                                dirInfo.FullName, "*.*", fileInfoCol, throwOnError)
  421.        Else
  422.            ' Search for all files.
  423.            SetupFileDirCollection(Of FileInfo)(AddressOf dirInfo.GetFiles, Nothing,
  424.                                                dirInfo.FullName, "*", fileInfoCol, throwOnError)
  425.        End If
  426.  
  427.        ' If the fileInfoCol collection is not empty then...
  428.        If fileInfoCol IsNot Nothing Then
  429.  
  430.            ' Iterate the files.
  431.            For Each fInfo As FileInfo In fileInfoCol
  432.  
  433.                ' Flag to determine whether a filename pattern is matched. Activated by default.
  434.                Dim flagNamePattern As Boolean = True
  435.  
  436.                ' Flag to determine whether a file extension pattern is matched. Activated by default.
  437.                Dim flagExtPattern As Boolean = True
  438.  
  439.                ' If filename patterns collection is not empty then...
  440.                If fileNamePatterns IsNot Nothing Then
  441.                    flagNamePattern = IsMatchPattern(fInfo.Name, fileNamePatterns, ignoreCase)
  442.                End If
  443.  
  444.                ' If file extension patterns collection is not empty then...
  445.                If fileExtPatterns IsNot Nothing Then
  446.                    flagExtPattern = IsMatchPattern(fInfo.Extension, fileExtPatterns, ignoreCase)
  447.                End If
  448.  
  449.                ' If fileName and also fileExtension patterns are matched then...
  450.                If flagNamePattern AndAlso flagExtPattern Then
  451.                    queue.Enqueue(fInfo) ' Enqueue this FileInfo object.
  452.                End If
  453.  
  454.            Next fInfo
  455.  
  456.        End If ' fileInfoCol IsNot Nothing
  457.  
  458.        ' If searchOption is recursive then...
  459.        If searchOption = searchOption.AllDirectories Then
  460.            RunNextTasks(Of FileInfo)(AddressOf CollectFiles,
  461.                                      queue, dirInfo.FullName, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  462.        End If
  463.  
  464.    End Sub
  465.  
  466.    ''' <summary>
  467.    ''' Collects the filepaths those matches the criteria inside the specified directory and/or sub-directories.
  468.    ''' </summary>
  469.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new filepaths.</param>
  470.    ''' <param name="dirPath">The root directory path to search for files.</param>
  471.    ''' <param name="searchOption">The searching mode.</param>
  472.    ''' <param name="fileNamePatterns">The file name pattern(s) to match.</param>
  473.    ''' <param name="fileExtPatterns">The file extension pattern(s) to match.</param>
  474.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="fileNamePatterns"/> and <paramref name="fileExtPatterns"/> patterns.</param>
  475.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to file or directory.</param>
  476.    Private Shared Sub CollectFilePaths(ByVal queue As ConcurrentQueue(Of String),
  477.                                        ByVal dirPath As String,
  478.                                        ByVal searchOption As SearchOption,
  479.                                        ByVal fileNamePatterns As IEnumerable(Of String),
  480.                                        ByVal fileExtPatterns As IEnumerable(Of String),
  481.                                        ByVal ignoreCase As Boolean,
  482.                                        ByVal throwOnError As Boolean)
  483.  
  484.        ' Initialize a filepath collection.
  485.        Dim filePathCol As IEnumerable(Of String) = Nothing
  486.  
  487.        If fileExtPatterns IsNot Nothing Then
  488.            ' Decrease time execution by searching for files that has extension.
  489.            SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  490.                                              dirPath, "*.*", filePathCol, throwOnError)
  491.        Else
  492.            ' Search for all files.
  493.            SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetFiles,
  494.                                              dirPath, "*", filePathCol, throwOnError)
  495.        End If
  496.  
  497.        ' If the filepath collection is not empty then...
  498.        If filePathCol IsNot Nothing Then
  499.  
  500.            ' Iterate the filepaths.
  501.            For Each filePath As String In filePathCol
  502.  
  503.                ' Flag to determine whether a filename pattern is matched. Activated by default.
  504.                Dim flagNamePattern As Boolean = True
  505.  
  506.                ' Flag to determine whether a file extension pattern is matched. Activated by default.
  507.                Dim flagExtPattern As Boolean = True
  508.  
  509.                ' If filename patterns collection is not empty then...
  510.                If fileNamePatterns IsNot Nothing Then
  511.                    flagNamePattern = IsMatchPattern(Path.GetFileNameWithoutExtension(filePath), fileNamePatterns, ignoreCase)
  512.                End If
  513.  
  514.                ' If file extension patterns collection is not empty then...
  515.                If fileExtPatterns IsNot Nothing Then
  516.                    flagExtPattern = IsMatchPattern(Path.GetExtension(filePath), fileExtPatterns, ignoreCase)
  517.                End If
  518.  
  519.                ' If fileName and also fileExtension patterns are matched then...
  520.                If flagNamePattern AndAlso flagExtPattern Then
  521.                    queue.Enqueue(filePath) ' Enqueue this filepath.
  522.                End If
  523.  
  524.            Next filePath
  525.  
  526.        End If ' filePathCol IsNot Nothing
  527.  
  528.        ' If searchOption is recursive then...
  529.        If searchOption = searchOption.AllDirectories Then
  530.            RunNextTasks(Of String)(AddressOf CollectFilePaths,
  531.                                    queue, dirPath, fileNamePatterns, fileExtPatterns, ignoreCase, throwOnError)
  532.        End If
  533.  
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Collects the directories those matches the criteria inside the specified directory and/or sub-directories.
  538.    ''' </summary>
  539.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of DirectoryInfo)"/> instance to enqueue new directories.</param>
  540.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  541.    ''' <param name="searchOption">The searching mode.</param>
  542.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  543.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  544.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  545.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  546.    Private Shared Sub CollectDirs(ByVal queue As ConcurrentQueue(Of DirectoryInfo),
  547.                                   ByVal dirPath As String,
  548.                                   ByVal searchOption As SearchOption,
  549.                                   ByVal dirPathPatterns As IEnumerable(Of String),
  550.                                   ByVal dirNamePatterns As IEnumerable(Of String),
  551.                                   ByVal ignoreCase As Boolean,
  552.                                   ByVal throwOnError As Boolean)
  553.  
  554.        ' Initialize a DirectoryInfo collection.
  555.        Dim dirInfoCol As IEnumerable(Of DirectoryInfo) = Nothing
  556.  
  557.        ' Initialize a DirectoryInfo.
  558.        Dim dirInfo As DirectoryInfo = Nothing
  559.        SetupDirInfoObject(dirPath, dirInfo, throwOnError)
  560.  
  561.        ' Get the top directories of the current directory.
  562.        SetupFileDirCollection(Of DirectoryInfo)(AddressOf dirInfo.GetDirectories, Nothing,
  563.                                                 dirInfo.FullName, "*", dirInfoCol, throwOnError)
  564.  
  565.        ' If the fileInfoCol collection is not empty then...
  566.        If dirInfoCol IsNot Nothing Then
  567.  
  568.            ' Iterate the files.
  569.            For Each dir As DirectoryInfo In dirInfoCol
  570.  
  571.                ' Flag to determine whether a directory path pattern is matched. Activated by default.
  572.                Dim flagPathPattern As Boolean = True
  573.  
  574.                ' Flag to determine whether a directory name pattern is matched. Activated by default.
  575.                Dim flagNamePattern As Boolean = True
  576.  
  577.                ' If directory path patterns collection is not empty then...
  578.                If dirPathPatterns IsNot Nothing Then
  579.                    flagPathPattern = IsMatchPattern(dir.FullName, dirPathPatterns, ignoreCase)
  580.                End If
  581.  
  582.                ' If directory name patterns collection is not empty then...
  583.                If dirNamePatterns IsNot Nothing Then
  584.                    flagNamePattern = IsMatchPattern(dir.Name, dirNamePatterns, ignoreCase)
  585.                End If
  586.  
  587.                ' If directory path and also directory name patterns are matched then...
  588.                If flagPathPattern AndAlso flagNamePattern Then
  589.                    queue.Enqueue(dir) ' Enqueue this DirectoryInfo object.
  590.                End If
  591.  
  592.            Next dir
  593.  
  594.        End If ' dirInfoCol IsNot Nothing
  595.  
  596.        ' If searchOption is recursive then...
  597.        If searchOption = searchOption.AllDirectories Then
  598.            RunNextTasks(Of DirectoryInfo)(AddressOf CollectDirs,
  599.                                           queue, dirPath, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  600.        End If
  601.  
  602.    End Sub
  603.  
  604.    ''' <summary>
  605.    ''' Collects the directory paths those matches the criteria inside the specified directory and/or sub-directories.
  606.    ''' </summary>
  607.    ''' <param name="queue">The <see cref="ConcurrentQueue(Of String)"/> instance to enqueue new directory paths.</param>
  608.    ''' <param name="dirPath">The root directory path to search for directories.</param>
  609.    ''' <param name="searchOption">The searching mode.</param>
  610.    ''' <param name="dirPathPatterns">The directory path pattern(s) to match.</param>
  611.    ''' <param name="dirNamePatterns">The directory name pattern(s) to match.</param>
  612.    ''' <param name="ignoreCase">If <c>True</c>, ignores the comparing case of <paramref name="dirPathPatterns"/> and <paramref name="dirNamePatterns"/> patterns.</param>
  613.    ''' <param name="throwOnError">If set to <c>true</c>, exceptions will be thrown, like access denied to directory.</param>
  614.    Private Shared Sub CollectDirPaths(ByVal queue As ConcurrentQueue(Of String),
  615.                                       ByVal dirPath As String,
  616.                                       ByVal searchOption As SearchOption,
  617.                                       ByVal dirPathPatterns As IEnumerable(Of String),
  618.                                       ByVal dirNamePatterns As IEnumerable(Of String),
  619.                                       ByVal ignoreCase As Boolean,
  620.                                       ByVal throwOnError As Boolean)
  621.  
  622.        ' Initialize a directory paths collection.
  623.        Dim dirPathCol As IEnumerable(Of String) = Nothing
  624.  
  625.        ' Get the top directory paths of the current directory.
  626.        SetupFileDirCollection(Of String)(Nothing, AddressOf Directory.GetDirectories,
  627.                                          dirPath, "*", dirPathCol, throwOnError)
  628.  
  629.        ' If the fileInfoCol collection is not empty then...
  630.        If dirPathCol IsNot Nothing Then
  631.  
  632.            ' Iterate the files.
  633.            For Each dir As String In dirPathCol
  634.  
  635.                ' Flag to determine whether a directory path pattern is matched. Activated by default.
  636.                Dim flagPathPattern As Boolean = True
  637.  
  638.                ' Flag to determine whether a directory name pattern is matched. Activated by default.
  639.                Dim flagNamePattern As Boolean = True
  640.  
  641.                ' If directory path patterns collection is not empty then...
  642.                If dirPathPatterns IsNot Nothing Then
  643.                    flagPathPattern = IsMatchPattern(dir, dirPathPatterns, ignoreCase)
  644.                End If
  645.  
  646.                ' If directory name patterns collection is not empty then...
  647.                If dirNamePatterns IsNot Nothing Then
  648.                    flagNamePattern = IsMatchPattern(Path.GetFileName(dir), dirNamePatterns, ignoreCase)
  649.                End If
  650.  
  651.                ' If directory path and also directory name patterns are matched then...
  652.                If flagPathPattern AndAlso flagNamePattern Then
  653.                    queue.Enqueue(dir) ' Enqueue this directory path.
  654.                End If
  655.  
  656.            Next dir
  657.  
  658.        End If ' dirPathCol IsNot Nothing
  659.  
  660.        ' If searchOption is recursive then...
  661.        If searchOption = searchOption.AllDirectories Then
  662.            RunNextTasks(Of String)(AddressOf CollectDirPaths,
  663.                                    queue, dirPath, dirPathPatterns, dirNamePatterns, ignoreCase, throwOnError)
  664.        End If
  665.  
  666.    End Sub
  667.  
  668. #End Region
  669.  
  670. End Class
  671.  
  672. #End Region
5792  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 14 Febrero 2015, 17:12 pm
Tras analizar diversos enfoques de iteradores y paralelismo para optimizar la manera de buscar archivos/carpetas, y aunque al final he preferido no programar las funciones de manera asíncrona, les presento el método definitivo (bueno, o casi xD) para buscar archivos/directorios de manera sencilla, personalizada, omitiendo y/o controlando errores de permisos de usuario (eso si, de forma básica, quien quiera puede añadirle eventos para un mayor control), y realizando una búsqueda muy, muy rápida al dividir el trabajo en varios threads, de esta manera disminuirán el tiempo de ejecución hasta un 400% en las búsquedas de archivos por ejemplo sería muy útil en aplicaciones de tipo USB-Stealer, donde es primordial la rápidez del algoritmo sin dejar de lado la eficiencia del mismo.

Modo de empleo:

Código
  1. Dim filePaths As List(Of String) = FileDirSearcher.GetFilePaths("C:\Windows\System32", SearchOption.AllDirectories).ToList
  2. Dim dirPaths As List(Of String) = FileDirSearcher.GetDirPaths("C:\Windows\System32", SearchOption.AllDirectories).ToList

o:
Código
  1. Dim files As List(Of FileInfo) = FileDirSearcher.GetFiles("C:\Windows\System32", SearchOption.AllDirectories).ToList
  2. Dim dirs As List(Of DirectoryInfo) = FileDirSearcher.GetDirs("C:\Windows\System32", SearchOption.AllDirectories).ToList

o:
Código
  1. Dim files As IEnumerable(Of FileInfo) = FileDirSearcher.GetFiles(dirPath:="C:\Windows\System32",
  2.                                                                 searchOption:=SearchOption.TopDirectoryOnly,
  3.                                                                 fileNamePatterns:={"*"},
  4.                                                                 fileExtPatterns:={"*.dll", "*.exe"},
  5.                                                                 ignoreCase:=True,
  6.                                                                 throwOnError:=True)
  7.  
  8. Dim dirs As IEnumerable(Of DirectoryInfo) = FileDirSearcher.GetDirs(dirPath:="C:\Windows\System32",
  9.                                                                    searchOption:=SearchOption.TopDirectoryOnly,
  10.                                                                    dirPathPatterns:={"*"},
  11.                                                                    dirNamePatterns:={"*Microsoft*"},
  12.                                                                    ignoreCase:=True,
  13.                                                                    throwOnError:=True)
  14.  

Source: http://pastebin.com/yrcvG7LP

EDITO: Versión anterior del código fuente de este Snippet (no tiene ninguna mejora implementada), por si quieren comparar los tiempos de espera de búsqueda: http://pastebin.com/Wg5SHdmS
5793  Programación / Programación Visual Basic / Re: Me arroja error "Sub or function not defined" en: 12 Febrero 2015, 11:37 am
no funciona

¿Que significa "no funciona"?, da detalles sobre lo que sucede, muestra el error (si alguno).

No hagas que nadie tenga que repetirte de nuevo el punto sobre DAR INFORMACIÓN, por favor.

Saludos...
5794  Programación / Programación Visual Basic / Re: Me arroja error "Sub or function not defined" en: 12 Febrero 2015, 11:14 am
me van a ayudar o no para irme a otro lugar?


1) Bájate los humos, la gente te ha respondido a tu post con buena fé para intentar averiguar más datos sobre el problema, porque no puedes ir por ahí formulando una pregunta de programación sin dar NINGÚN tipo de información, y más cuando se trata de un maldito error, que el compiler te está indicando el motivo del error pero ha hecho falta que un compañero te pida esos datos BÁSICOS para que lo compartieses, ¿que narices esperas, que hagamos de adivinos?, deberías sentirte agradecido por que más de 1 usuario haya prestado atención a un post de tan poca calidad (carente de cualquier información sobre el problema) y encima se haya tomado la molesta de responderte.

El caso es que, YA TE ESTÁN AYUDANDO, así que no es necesario que te dirijas con prepotencia a las personas que te están ofreciendo ayuda, si eres una persona impaciente, pues lo siento por ti, si quieres irte, vete, nadie te obliga a quedarte, pero diciendo esas cosas no conseguirás NADA, bueno, si, conseguirás todo lo contrario a lo que tanto andas buscando (que no te ayuden).

En serio, ¿tu crees que es normal que un moderador global tenga que pedirte información porque llegaste sin mostrar nada, y luego el moderador de la sección tenga que pedirte explicaciones sobre lo que intentas hacer porque tampoco especificaste nada? (y que además te estemos llamando la atención por quebrantamientos de las reglas del foro), el problema no es de ellos, sino tuyo, así que relájate un poco y habla con propiedad, este es un lugar respetable, si quieres ayuda, colaboras dando la información necesaria, no nos hagas perder el tiempo haciendóte preguntas que deberías haber resuelto por ti mismo al formular el post.

Te invito a leer lo siguiente:
Citar



2) Debes seguir las normas del foro, profavor no publiques posts duplicados y encima en la sección incorrecta, sabes perfectamente donde debes postear las preguntas sobre VB6.



3) Me imagino que la intención del miembro inexistente "MUTEX", como su nombre indica, sería para asignarle un MUTEX a la instancia de la aplicación, ¿tienes idea de lo que significa eso? (lo pregunto en serio, ¿aparte de copiar todo el código, te has parado a intentar examinarlo para aprender su funcionamiento?, lee acerca de Mutex y Sempahores ), simplemente elimina esa instrucción para que te compile correctamente, en un principio es irrelevante dado que tus intenciones no son manipular el Mutex de la app.


Saludos.
5795  Programación / .NET (C#, VB.NET, ASP) / Re: Compilación C# - Estructuras Dinamicas en: 12 Febrero 2015, 10:30 am
Osea lo que se pide es que el usuario ingrese datos a la pila indefinidamente, hasta que llegue el momento en donde decida que ya no desea ingresar, mas datos.

Espero contar con tu valioso apoyo, saludos cordiales.   :D

Entonces simplemente omite la comprobación de la cantidad de elementos en la pila :-/, quitando esa condicional en el código de ejemplo que mostré, el código hará lo que pides.

Saludos!
5796  Programación / .NET (C#, VB.NET, ASP) / Re: vb.net - Items Duplicados y no duplicados de Un Listview en: 12 Febrero 2015, 06:30 am
Puedes utilizar LINQ para llevarlo a cabo:

Código
  1. Public Class TestForm
  2.  
  3.    ReadOnly items As IEnumerable(Of String) =
  4.        {
  5.            "Informe1.docx",
  6.            "Informe2.docx",
  7.            "Informe3.docx",
  8.            "Presentacion_1.pptx",
  9.            "Presentacion_2.docx",
  10.            "Presentacion_2.docx",
  11.            "Proyecto1.docx",
  12.            "Proyecto1.docx"
  13.        }
  14.  
  15.    Private allDups As IEnumerable(Of String) =
  16.        items.GroupBy(Function(str As String) str).
  17.              Where(Function(group As IGrouping(Of String, String)) group.Count > 1).
  18.              SelectMany(Function(group As IGrouping(Of String, String)) group)
  19.  
  20.    Private uniqueDups As IEnumerable(Of String) =
  21.        items.GroupBy(Function(str As String) str).
  22.              Where(Function(group As IGrouping(Of String, String)) group.Count > 1).
  23.              Select(Function(group As IGrouping(Of String, String)) group.Key)
  24.  
  25.    Private nonDups As IEnumerable(Of String) =
  26.        items.Distinct
  27.  
  28.    Private unique As IEnumerable(Of String) =
  29.        items.Except(uniqueDups)
  30.  
  31.    Private Sub Test() Handles MyBase.Shown
  32.  
  33.        With Me.ListBox1
  34.            .Sorted = True
  35.            .BeginUpdate()
  36.            .Items.AddRange(items.ToArray) ' Todos.
  37.            ' .Items.AddRange(nonDups.ToArray) ' Sin Duplicados.
  38.            ' .Items.AddRange(unique.ToArray) ' Únicos.
  39.            ' .Items.AddRange(allDups.ToArray) ' Duplicados.
  40.            ' .Items.AddRange(uniqueDups.ToArray) ' Duplicados Únicos.
  41.            .EndUpdate()
  42.        End With
  43.  
  44.    End Sub
  45.  
  46. End Class


Output


Todos:
Código:
Informe1.docx
Informe2.docx
Informe3.docx
Presentacion_1.pptx
Presentacion_2.docx
Presentacion_2.docx
Proyecto1.docx
Proyecto1.docx

Sin Duplicados:
Código:
Informe1.docx
Informe2.docx
Informe3.docx
Presentacion_1.pptx
Presentacion_2.docx
Proyecto1.docx

Únicos:
Código:
Informe1.docx
Informe2.docx
Informe3.docx
Presentacion_1.pptx

Duplicados:
Código:
Presentacion_2.docx
Presentacion_2.docx
Proyecto1.docx
Proyecto1.docx

Duplicados Únicos:
Código:
Presentacion_2.docx
Proyecto1.docx


Saludos!
5797  Programación / Scripting / Re: variables en batch en: 11 Febrero 2015, 20:04 pm
pero entoncs Elektro porque no puedo pasar a una variable %v1% el valor del %%i
Muestra el código donde manejas las variables, el output, y te diré el por qué xD.

La razón más común te la he explicado, a veces una aplicación externa agrega una linea final en blanco a la salida, a veces no percibimos esa linea vacía, y pasa eso.
Pero podría haber más motivos, como por ejemplo utilizar esa variable dentro del for sin haberla expandido, aunque esa no es la causa al menos en el código que has mostrado arriba.
EDITO: También podría deberse a que el output de sqlplus tuviera una codificación Unicode, y eso necesitaría otro tipo de tratamiento en la variable, ya que podría estar asignandose un valor "nulo" (en blanco).


cuando intento de usar la variable, %%i DENTRO DEL FOR POR EJEMPLO NO HAY PROBLEMA, PERO FUERA DEL FOR, AL LLAMAR A LA VARIABLE NO TIENE VALOR
Es que la variable %%i es una variable especial de For, no tiene vida fuera del bloque For, por otro lado, la variable "valor", como ya he comentado, si que sigue existiendo.


mira te explico, lo que estoy intentando de hacer es que, si la tabla errores_geom no tiene nada, siga corriendo un procedimiento, pero si esta tabla tiene un registro al menos, no siga corriendo el procedimiento, y salte a la siguiente archivo para proceder a validar si tiene errores, si tiene errores, la tabla se llena y nuevamente, salta a la siguiente archivo, esto debe tener una salida, para que la persona sepa porque se cayo para este archivo y si no le entregara los resultados esperados, tengo listo la lectura de los archivos, pasa uno por uno, el problema es que a veces esos archivos que son dibujados por personas tienen errores, por lo tanto debo ingresar esa validacion, lo que necesito es pasar el valor de esa query entregarla a una variable, para usarla indiscriminadamente, entre todos los batch que necesito usar, asi tbn puedo sacar el nombre de las comunas, que tambien esta almacenado en una BD, si me puedes dar alguna otra idea de como entregarle a una variable el valor de la query mas arriba, esa query solo muestra un valor, porque como indicaba es un count de la tabla, ojalas me puedas hechar una mano, o algun otro que me pueda ayudar, gracias

Lo siento pero como ya te digo no manejo sql/sqlplus, desconozco cual es el output que envia la aplicaicón sqlplus porque también desconozco la funcionalidad y el comportamiento de los parámetros que estás utilizando al ejecutar esa aplicación mediante la consola, aunque me hago una ligera idea no puedo evaluarlo correctamente, solo te puedo ayudar y/o orientar en lo otro.

Haz una cosa, envia la salida de la aplicación sqlplus.exe a un archivo de texto plano:
Código:
(sqlplus -s QA_DATAC/qa_dc@orcl_qa @%PATH_SQL%t1)>"archivo.txt"

Comprueba si el texto resultante contiene lineas vacias al final del archivo, en caso de tener lineas vacias (o con espacios en blanco) ya te indiqué como corregir el problema con la variable "valor", en caso contrario, muestra más detalles del código bat, muestra también el output de la tabla que se ha enviado al archivo de texto, y por último indica que valor de la salida es la que intentas asignar a la variable "valor".

Saludos!
5798  Programación / Scripting / Re: variables en batch en: 11 Febrero 2015, 18:54 pm
Cualquier variable que inicialices dentro del For seguirá existiendo tras finalizar el bloque del FOR, ¿por que piensas que no es así?,
otra cosa muy distinta sería que el output de la aplicación sqlplus.exe tuviera más de una linea, con una linea final en blanco, y en ese caso el For, al iterar las lineas, se estaría sobre-escribiendo el valor de la variable, al final asignando un valor vacio.

Asegúrate de filtrar lineas vacías y/o en blanco del output, de la siguiente manera:
Código:
For ... in (`sqlplus -s QA_DATAC/qa_dc@orcl_qa @%PATH_SQL%t1 ^| findstr "^[^\s]"`) Do (...)
Nota: Ten en cuenta que en el código que has mostrado estás utilizando el modificador UseBackQ en el For, y eso altera el comportamiento de las comillas dobles, no manejo sqlplus, pero creo que no necesites usarlo.

Además de eso, estás dejando un espacio en blanco a la derecha del operador de asignación (Set valor= %%i)), corrígelo, utiliza la sintaxis correcta: Set "valor=%%~i".

Saludos
5799  Programación / .NET (C#, VB.NET, ASP) / Re: Compilación C# - Estructuras Dinamicas en: 11 Febrero 2015, 15:55 pm
como realizo las modificaciones para ... permitir ingresar más datos a la pila

Sabiendo de antemano que dicho código en su estructura se encuentra limitado a insertar tres elementos en la pila.

¿Lo que quieres es limitar la inserción de elementos en la pila a un total de 3 elementos?, entonces:

Código
  1. Stack myStack = new Stack();
  2. int maxStackCount = 3;
  3.  
  4. ...
  5.  
  6. case 1:
  7.  if (mySatck.Count < maxStackCount) {
  8.    // Pedimos el valor a introducir
  9.  } else {
  10.    Console.WriteLine(string.Format("La pila no puede exceder más de {0} elementos.", maxStackCount));
  11.  }

EDITO: En el código que has mostrado no has acondicionado un 'case 5' para detener la inserción de datos en la pila, ¿a sido un descuido por tu parte, o necesitas ayuda con eso?.
EDITO 2: Además, si introduces una opción "erronea", tal y como tienes el búcle no va a permitir "intentarlo de nuevo" como se supone que especificas en un mensaje de la consola xD.

Traslada todas las instruccones del código que has msotrado para trabajarlo en un bloque distinto al punto de entrada de la aplicación, prueba así:

VB.Net
Código
  1. Imports System.Text
  2.  
  3. Module Module1
  4.  
  5.    Dim myStack As New Stack
  6.    Dim maxStackCount As Integer = 3
  7.  
  8.    Sub Main()
  9.        Choose()
  10.    End Sub
  11.  
  12.    Private Sub Choose()
  13.  
  14.        Dim userInput As Char
  15.        Dim userValue As Integer = 0
  16.  
  17.        Dim sb As New StringBuilder
  18.        sb.AppendLine("1- Push")
  19.        sb.AppendLine("2- Pop")
  20.        sb.AppendLine("3- Clear")
  21.        sb.AppendLine("4- Contains")
  22.        sb.AppendLine("5- Salir")
  23.        sb.AppendLine("Dame tu opcion")
  24.  
  25.        Do Until Not Enumerable.Range(0, 5).Contains(userValue)
  26.  
  27.            Console.WriteLine(sb.ToString)
  28.  
  29.            userInput = Console.ReadKey().KeyChar
  30.            Integer.TryParse(userInput, userValue)
  31.  
  32.            Select Case userValue
  33.  
  34.                Case 1
  35.                    If myStack.Count < maxStackCount Then
  36.                        ' Pedimos el valor a introducir
  37.                    Else
  38.                        Console.WriteLine(String.Format("La pila no puede exceder más de {0} elementos", maxStackCount))
  39.                    End If
  40.  
  41.                Case 2
  42.                    ' Obtnemos el elemento.
  43.  
  44.                Case 3
  45.                    ' Limpiamos todos los contenidos del stack.
  46.  
  47.                Case 4
  48.                    ' Pedimos el valor a encontrar.
  49.  
  50.                Case 5
  51.                    ' Salimos del búcle.
  52.                    Exit Do
  53.  
  54.                Case Else
  55.                    userValue = 0 ' Resetear el valor para no salir del bucle.
  56.                    Console.Clear()
  57.                    Console.WriteLine("No existe la opción, intente de nuevo")
  58.  
  59.            End Select
  60.  
  61.        Loop
  62.  
  63.        sb.Clear()
  64.  
  65.    End Sub
  66.  
  67. End Module

Traducción a C#:
Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.Text;
  8.  
  9. static class Module1
  10. {
  11.  
  12. static Stack myStack = new Stack();
  13.  
  14. static int maxStackCount = 3;
  15.        static void Main(string[] args)
  16. {
  17. Interaction.Choose();
  18. }
  19.  
  20. private static void Choose()
  21. {
  22. char userInput = '\0';
  23. int userValue = 0;
  24.  
  25. StringBuilder sb = new StringBuilder();
  26. sb.AppendLine("1- Push");
  27. sb.AppendLine("2- Pop");
  28. sb.AppendLine("3- Clear");
  29. sb.AppendLine("4- Contains");
  30. sb.AppendLine("5- Salir");
  31. sb.AppendLine("Dame tu opcion");
  32.  
  33. while (!(!Enumerable.Range(0, 5).Contains(userValue))) {
  34. Console.WriteLine(sb.ToString);
  35.  
  36. userInput = Console.ReadKey().KeyChar;
  37. int.TryParse(userInput, userValue);
  38.  
  39. switch (userValue) {
  40.  
  41. case 1:
  42. if (myStack.Count < maxStackCount) {
  43. // Pedimos el valor a introducir
  44. } else {
  45. Console.WriteLine(string.Format("La pila no puede exceder más de {0} elementos", maxStackCount));
  46. }
  47. break;
  48.  
  49. case 2: // Obtnemos el elemento.
  50. break;
  51.  
  52. case 3: // Limpiamos todos los contenidos del stack.
  53. break;
  54.  
  55. case 4: // Pedimos el valor a encontrar.
  56. break;
  57.  
  58. case 5: // Salimos del búcle.
  59. userValue = -1;
  60. break;
  61.  
  62. default:
  63. userValue = 0; // Resetear el valor para no salir del bucle.
  64. Console.Clear();
  65. Console.WriteLine("No existe la opción, intente de nuevo");
  66. break;
  67. }
  68. }
  69. sb.Clear();
  70. }
  71. }
  72.  
  73. //=======================================================
  74. //Service provided by Telerik (www.telerik.com)
  75. //=======================================================

Saludos!
5800  Programación / .NET (C#, VB.NET, ASP) / Re: abrir desde la fila de un Datagridview en: 11 Febrero 2015, 15:28 pm
en tu código veo que en la parte de arriba del evento CellContentClick tienes un código que supongo yo es para llenar el datagridview (aun que lo estoy dudando, creo que es parde del codigo para que lo de abajo me funcione correctamente)

No te preocupes, era un simple relleno del DataGridView para mostrarte un código funcional.


las tres palabras que subraye dentro del evento CellContentClick me marcan error bro, porfa ayudame  

Debes seguir las normas del foro para utilizar las etiquetas al insertar código.

Puedes utilizar los parámetros de las etiquetas para resaltar lineas del código como puedes ver en tu comentario que he editado arriba, o puedes especificar exactamente los nombres.

Dicho esto, si el compiler te está indicando un error y además te está mostrando la causa del error y la información adicional sobre el mismo, ¿porque no muestras la información sobre el error?, no soy adivino.

De todas formas, por los nombres que subrayaste, deduzco que seguramente los errores sean porque no hayas importado los namespaces necesarios.
Código
  1. Using System.IO; // File
  2. Using System.Diagnostics; // Process
  3. Using System.Windows.Forms; // DataGridView.Rows

...Pero es que como ya he explicado puedes comprobar la causa de esos errores sin necesidad de ayuda, muestra la info del error si necesitas ayuda para solucionarlos en caso de que el error no sea por la ausencia de los namespaces.

Saludos!
Páginas: 1 ... 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 [580] 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines