[RESOLVED] [2005] Why isn't this searching the root folder?
Hi,
Can anybody tell me why this bit of code is ignoring the root folder?
Code:
Private Function GetAllFolders(ByVal folder As String) As String()
For Each strFolder As String In Directory.GetDirectories(folder, "*", SearchOption.TopDirectoryOnly)
Try
strAllFolders.AddRange(GetAllFolders(strFolder))
SearchIn(strFolder)
Catch ex As Exception
' Ignore
End Try
Next
Return strAllFolders.ToArray
End Function
Re: [2005] Why isn't this searching the root folder?
You are searching within the root directory so your loop wont return the root folder itself.
Re: [2005] Why isn't this searching the root folder?
Is there a way to make it return the root folder?
Re: [2005] Why isn't this searching the root folder?
isn't that just the 'folder' variable, which you would obviously already know having passed the root path in the first place?
Re: [2005] Why isn't this searching the root folder?
Yes it is, but I couldn't get it to even think about using 'folder'.
To solve it, I've had to break it up a bit by creating a boolean value to MAKE it use 'folder', and once it has been used, change the boolean so that it processes strFolder.
Not nice, but its the only way I could think of getting it to work.
Re: [2005] Why isn't this searching the root folder?
So what you're saying is that you want the root folder included in the array returned by the method, correct?
vb.net Code:
Private Function GetFolders(ByVal folder As String) As String()
Dim folders As New List(Of String)
folders.Add(folder)
Try
For Each subfolder As String In IO.Directory.GetDirectories(folder)
folders.AddRange(Me.GetFolders(subfolder))
Next subfolder
Catch
'This folder is inaccessible so ignore it and move on.
End Try
Return folders.ToArray()
End Function
Re: [2005] Why isn't this searching the root folder?
Thanks. This works - although it is practically identical to how my code originally looked.
Can't claim that I fully understand it at this stage.
Re: [RESOLVED] [2005] Why isn't this searching the root folder?
This is what your code was doing:
1. Add all the subfolders of the specified to the list.
2. Make a recursive call for each subfolder.
That's why the top-level folder was never added: because the first call to the method ignored the specified folder and started by adding the subfolders. This is what my code is doing:
1. Add the specified folder to the list.
2. Make a recursive call for each subfolder.
Thus my code will start by adding the top-level folder to the list, which is exactly what you want. In my code each folder will be added to the list one recursive call later than it will in yours.