Results 1 to 11 of 11

Thread: [RESOLVED] Not sure how to use this.

  1. #1

    Thread Starter
    Frenzied Member Pc_Not_Mac's Avatar
    Join Date
    Oct 2009
    Location
    localhost
    Posts
    1,206

    Resolved [RESOLVED] Not sure how to use this.

    I found a file recursive directory function, but i'm not sure how to start it
    Any ideas?

    Code:
    Imports System.IO
    
    ''' <summary>
    ''' This class contains directory helper method(s).
    ''' </summary>
    Public Class FileHelper
    
        ''' <summary>
        ''' This method starts at the specified directory, and traverses all subdirectories.
        ''' It returns a List of those directories.
        ''' </summary>
        Public Shared Function GetFilesRecursive(ByVal initial As String) As List(Of String)
            ' This list stores the results.
            Dim result As New List(Of String)
    
            ' This stack stores the directories to process.
            Dim stack As New Stack(Of String)
    
            ' Add the initial directory
            stack.Push(initial)
    
            ' Continue processing for each stacked directory
            Do While (stack.Count > 0)
                ' Get top directory string
                Dim dir As String = stack.Pop
                Try
                    ' Add all immediate file paths
                    result.AddRange(Directory.GetFiles(dir, "*.*"))
    
                    ' Loop through all subdirectories and add them to the stack.
                    Dim directoryName As String
                    For Each directoryName In Directory.GetDirectories(dir)
                        stack.Push(directoryName)
                    Next
    
                Catch ex As Exception
                End Try
            Loop
    
            ' Return the list
            Return result
        End Function
    
    End Class
    
    Module Module1
    
        ''' <summary>
        ''' Entry point that shows usage of recursive directory function.
        ''' </summary>
        Sub Main()
            ' Get recursive List of all files starting in this directory.
            Dim list As List(Of String) = FileHelper.GetFilesRecursive("C:\Users\Sam\Documents\Perls")
    
            ' Loop through and display each path.
            For Each path In list
                Console.WriteLine(path)
            Next
    
            ' Write total number of paths found.
            Console.WriteLine(list.Count)
        End Sub
    
    End Module
    My Codebank:
    Windows Vista & 7 Glass Effect & Limit the amount of times your application could be opened.
    Pause Your Code & Check the OS name

    The question of whether computers can think is like the question of whether submarines can swim.

    Currently learning: Java

    Coding can be a learning experience or

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: Not sure how to use this.

    Dim ListOfFiles = FileHelper.GetFilesRecursive(<path of directory to start searching>)

    That should work.
    My usual boring signature: Nothing

  3. #3
    Lively Member
    Join Date
    Apr 2010
    Location
    Australia
    Posts
    71

    Re: Not sure how to use this.

    You can use the static GetFiles method of the Directory class & specify the last parameter as "SearchOption.AllDirectories". This will search recursively.

    Code:
    Dim myDirectories As String() = Directory.GetFiles("C:\", "*.*", SearchOption.AllDirectories)

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Not sure how to use this.

    Quote Originally Posted by Mickroy View Post
    You can use the static GetFiles method of the Directory class & specify the last parameter as "SearchOption.AllDirectories". This will search recursively.

    Code:
    Dim myDirectories As String() = Directory.GetFiles("C:\", "*.*", SearchOption.AllDirectories)
    That code will throw an exception when it inevitably encounters an inaccessible folder. If there's any chance of finding an inaccessible folder along the way then you must do the recursion yourself, so that you can handle the exception and continue.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  5. #5

    Thread Starter
    Frenzied Member Pc_Not_Mac's Avatar
    Join Date
    Oct 2009
    Location
    localhost
    Posts
    1,206

    Re: Not sure how to use this.

    Thank you for the reply.
    Looks like the:
    Dim ListOfFiles = FileHelper.GetFilesRecursive("C:\")
    starts the "engine" and freezes the frm.
    Which i was thinking of adding it to a background worker to start that process on a different thread so that the user still could interact with the main GUI.
    But, one problem even if i change C:\ to C:\test which only has one file in my case it still does not display found files on the listbox1.

    The code:
    Code:
    Imports System.IO
    
    ''' <summary>
    ''' This class contains directory helper method(s).
    ''' </summary>
    Public Class FileHelper
    
        ''' <summary>
        ''' This method starts at the specified directory, and traverses all subdirectories.
        ''' It returns a List of those directories.
        ''' </summary>
        Public Shared Function GetFilesRecursive(ByVal initial As String) As List(Of String)
            ' This list stores the results.
            Dim result As New List(Of String)
    
            ' This stack stores the directories to process.
            Dim stack As New Stack(Of String)
    
            ' Add the initial directory
            stack.Push(initial)
    
            ' Continue processing for each stacked directory
            Do While (stack.Count > 0)
                ' Get top directory string
                Dim dir As String = stack.Pop
                Try
                    ' Add all immediate file paths
                    result.AddRange(Directory.GetFiles(dir, "*.*"))
    
                    ' Loop through all subdirectories and add them to the stack.
                    Dim directoryName As String
                    For Each directoryName In Directory.GetDirectories(dir)
                        stack.Push(directoryName)
                    Next
    
                Catch ex As Exception
                End Try
            Loop
    
            ' Return the list
            Return result
        End Function
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim ListOfFiles = FileHelper.GetFilesRecursive("C:\")
        End Sub
    End Class
    Module Module1

    Sub Main()
    ' Get recursive List of all files starting in this directory.
    Dim list As List(Of String) = FileHelper.GetFilesRecursive("C:\Windows")

    ' Loop through and display each path.
    For Each path In list
    FileHelper.ListBox1.Items.Add(path)
    MsgBox(path)
    Next

    ' Write total number of paths found.
    ' FileHelper.ListBox1.Items.Add(list.Count)
    End Sub

    End Module
    Can you see the problem?
    Thanks in advance.
    My Codebank:
    Windows Vista & 7 Glass Effect & Limit the amount of times your application could be opened.
    Pause Your Code & Check the OS name

    The question of whether computers can think is like the question of whether submarines can swim.

    Currently learning: Java

    Coding can be a learning experience or

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Not sure how to use this.

    Your code doesn't really make a lot of sense. You have a Main method in a module, which suggests that that would be the entry point for the app, yet you have at least one form but that Main method isn't creating a form, so the Main method obviously isn't the entry point. Besides that, you have a module calling a Shared method of a form to get a list of files and then displaying them in an instance of the same form class. Why would the form not just do that itself? What possible useful purpose could that module serve?

    I'll wager that the issue is that you are adding the items to the ListBox on the default instance of the form but it's not the default instance that you have displayed but it's hard to tell because your code is just a bit non-sensical. From a functionality perspective, what are you actually trying to achieve? For example:
    The user clicks a Button on a form and then selects a folder in a FolderBrowserDialog, then all files in and under that folder get displayed in a ListBox on the same form, without freezing the form in the process.
    That's the sort of succinct, i.e. brief but clear, description I'm looking for.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7

    Thread Starter
    Frenzied Member Pc_Not_Mac's Avatar
    Join Date
    Oct 2009
    Location
    localhost
    Posts
    1,206

    Re: Not sure how to use this.

    The user clicks a Button on a form and then selects a folder in a FolderBrowserDialog, then all files in and under that folder get displayed in a ListBox on the same form, without freezing the form in the process.
    That itself is not hard to make.
    The problem is that when access to file is denied then it errors out.
    So that's why I'm looking into GetFilesRecursive.
    I mean frm does freeze up so that means it's searching for something right.
    I have been always so confused with GetFilesRecursive.
    My Codebank:
    Windows Vista & 7 Glass Effect & Limit the amount of times your application could be opened.
    Pause Your Code & Check the OS name

    The question of whether computers can think is like the question of whether submarines can swim.

    Currently learning: Java

    Coding can be a learning experience or

  8. #8
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Not sure how to use this.

    I specifically asked for a description from you of what you're trying to achieve.
    From a functionality perspective, what are you actually trying to achieve?
    You provided no such description. I assume that those who don't answer my questions don;t want my help.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  9. #9

    Thread Starter
    Frenzied Member Pc_Not_Mac's Avatar
    Join Date
    Oct 2009
    Location
    localhost
    Posts
    1,206

    Re: Not sure how to use this.

    Thank you for the reply jmcilhinney.
    What I'm trying to do is to get all the files from specific directory.
    I was going to use the Getfiles method.
    The problem with that is when the code comes to a file that access is denied to its going to error out.
    So that's why I'm looking into the GetFilesRecursive to skip such error when it invokes.
    I just can't find a good example or article that would teach me.
    Any ideas?
    Thank you in advance.
    My Codebank:
    Windows Vista & 7 Glass Effect & Limit the amount of times your application could be opened.
    Pause Your Code & Check the OS name

    The question of whether computers can think is like the question of whether submarines can swim.

    Currently learning: Java

    Coding can be a learning experience or

  10. #10
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Not sure how to use this.

    That still doesn't answer my question so I'll just ignore that and address the recursion issue specifically. It's really very simple. The whole point of recursion is that you have a method that does something, then calls itself to do that thing again at a different level. In this case, you want a method that takes a folder path and gets all the files in that folder, then calls itself for each subfolder. Exactly how you implement it depends on what you want it to return. File.GetFiles retirns a String array so let's go with that.

    Step 1: Write a method that gets all the files in a folder and returns them as a String array:
    vb.net Code:
    1. Private Function GetFiles(ByVal folder As String) As String()
    2.     Dim files As String() = Directory.GetFiles(folder)
    3.  
    4.     Return files
    5. End Function
    Step 2: Make the function recursive by having it call itself for each subfolder:
    vb.net Code:
    1. Private Function GetFiles(ByVal folder As String) As String()
    2.     Dim files As New List(Of String)(Directory.GetFiles(folder))
    3.  
    4.     For Each subfolder As String In Directory.GetDirectories(folder)
    5.         'This is the recursive call.
    6.         files.AddRange(GetFiles(subfolder))
    7.     Next
    8.  
    9.     Return files.ToArray()
    10. End Function
    Notice that we now start with a List, so that we can add to it, but we still return an array.

    Step 3: Add exception handling to enable recursion to continue if an inaccessible folder is encountered:
    vb.net Code:
    1. Private Function GetFiles(ByVal folder As String) As String()
    2.     Dim files As New List(Of String)
    3.  
    4.     Try
    5.         files.AddRange(Directory.GetFiles(folder))
    6.  
    7.         For Each subfolder As String In Directory.GetDirectories(folder)
    8.             'This is the recursive call.
    9.             files.AddRange(GetFiles(subfolder))
    10.         Next
    11.     Catch
    12.         'This folder is inaccessible.  Ignore and continue.
    13.     End Try
    14.  
    15.     Return files.ToArray()
    16. End Function
    That's pretty much all there is to it.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  11. #11

    Thread Starter
    Frenzied Member Pc_Not_Mac's Avatar
    Join Date
    Oct 2009
    Location
    localhost
    Posts
    1,206

    Re: Not sure how to use this.

    Thank you for the code and the expiation jmcilhinney.
    I have been very confused with recursion function.
    My Codebank:
    Windows Vista & 7 Glass Effect & Limit the amount of times your application could be opened.
    Pause Your Code & Check the OS name

    The question of whether computers can think is like the question of whether submarines can swim.

    Currently learning: Java

    Coding can be a learning experience or

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width