View Single Post
  #1 (permalink)  
Old 12-02-2008, 9:30 AM
blackduck603's Avatar
blackduck603 blackduck603 is offline
VB.NET Forum Newbie
.NET Framework: .NET 1.1 (VS 2003)
 
Join Date: Sep 2008
Location: NH
Posts: 21
Reputation: 21
blackduck603 is on a distinguished programming path ahead
Default Trouble using recursion to process folders/files

I am trying to write code to save (in a text file) a list of folders/files that are contained in a specified folder. I want the list to be formatted to illustrate the folder tree structure by indenting sub-folders and there related files according to their relationship to the base folder.

I found and incorporated a recursive function for listing file & folders. This works fine for generating the list, but I am having difficulty with code to determine the sub-directory level relative to the base folder. the code that I have included below sort of works.......The problem seeme to be when going from a folder that is multiple levels up? from the base to one that is only one level from the base. Refer to my sample output.

This should not be as difficult as I seemed to have made it, but recursion kinda blows my mind.



Code:
' The following function call is in a button handler 
GetFilesFolders(txtBaseFolder.Text)

    Public Sub GetFilesFolders(ByVal path As String)        
        Write2Log("-------------------------------------------------------------")
        Write2Log(" F O L D E R    C O N T E N T S : ")
        Write2Log("-------------------------------------------------------------")

         If File.Exists(path) Then
            ' This path is a file 
            ProcessFile(path, 0)
        ElseIf Directory.Exists(path) Then
            ' This path is a directory 
            ProcessDirectory(path, 0) 
        End If
    End Sub

    Public Sub ProcessDirectory(ByVal targetDirectory As String, ByVal mySubDirLevel As Integer)
        ' Process all files/folders in the directory passed in, 
        ' recurse on any subdirectories that are found, and process the files they contain. 
        ' Write the file and folder info to a file 
        ' - indent based on Directory Level to simulate a Tree Hierarchy

        ' Spacing is used for indentation        
        Dim sSpacing As String = ""
        If mySubDirLevel > 0 Then
            For nIdx As Integer = 0 To mySubDirLevel
                sSpacing = sSpacing & "-"
            Next nIdx
        End If
        ' Write the info to a file        
        Write2Log(sSpacing & "[" & targetDirectory & "]")
        Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
        ' If there are files in the folder, get the info and write it to the output file        
        For Each fileName As String In fileEntries
            ProcessFile(fileName, sSpacing)
        Next

        ' Recurse into subdirectories of this directory.         
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)

        If subdirectoryEntries.Length > 0 Then
            For Each subdirectory As String In subdirectoryEntries
                Dim nSubDirLevel As Integer
                ' Get the subDir Level                
nSubDirLevel = GetDirLevel(subdirectory, Me.txtFolderToWatch.Text)
                ' RECURSE - Process the Directory
                ProcessDirectory(subdirectory, nSubDirLevel) 
            Next
        End If
    End Sub



' Global used to keep track of previous Dir Level
    Dim nDirLevelCounter As Integer = 1

    Public Function GetDirLevel(ByVal myPath As String, ByVal sBaseDir As String) As Integer
        ' This function is used to determine the relative SubDir level based on the BaseDir that is passed in
        ' For example: 
        ' if C:\Tmp\Base is the base Dir
        ' then 
        ' C:\Tmp\Base                           should return 0
        ' C:\Tmp\Base\SubDir1                   should return 1
        ' C:\Tmp\Base\SubDir1\Subdir1a\SubDirX  should return 3        
Dim sParentDir As String
        Dim diDir As System.IO.DirectoryInfo
        diDir = Directory.GetParent(myPath)
        sParentDir = diDir.FullName()
        If sParentDir = sBaseDir Then
            Return nDirLevelCounter
        Else
            nDirLevelCounter = nDirLevelCounter + 1
            Return GetDirLevel(sParentDir, sBaseDir)        
End If
    End Function

    Public Sub Write2Log(ByVal Msg As String)
        Dim sAppname As String
        Dim sLogFolder As String
        If My.Settings.LogFilePath = "" Then
            ' Use App Folder
            sLogFolder = CurrentDirectory
        Else
            sLogFolder = My.Settings.LogFilePath
        End If
        sAppname = Application.ProductName
        Dim objStreamWriter As StreamWriter
        objStreamWriter = File.AppendText(sLogFolder & "\" & sAppname & "-Log.txt")
        'Precede the Message with a Date/Time stamp
        objStreamWriter.WriteLine(Msg)
        'Close the stream
        objStreamWriter.Close()
    End Sub

Output file (my notes depicted with *)
Code:
-------------------------------------------------------------
 F O L D E R    C O N T E N T S : 
-------------------------------------------------------------
[C:\tmp\fsw]
----> 1TextDoc.txt
----> Import1125.txt
--[C:\tmp\fsw\Fldr1Lvl1]                        ** Level 1 (correct)
------> WaveLvl0.wav
------> ZipLvl0.zip
--[C:\tmp\fsw\Fldr2Lvl1]                        ** Level 1 (correct)
------> BitmapLvl1.bmp
---[C:\tmp\fsw\Fldr2Lvl1\Fldr1Lvl2]          ** Level 2 (correct)
-------> BitmapLvl2.bmp
-----[C:\tmp\fsw\Fldr2Lvl1\Fldr1Lvl2\Fldr1Lvl3]   ** Level 3 (correct)
---------> WaveLvl3.wav
-----[C:\tmp\fsw\Fldr3Lvl1]                       ** (wrong) Should be Level 1
---------> Wave3-1.wav
I appreciate any assistance that can be provided.
Reply With Quote