Наконец-то конвертировал мою версию VB.NET в C #:
namespace ExtensionMethods
{
public static class DirectoryExtensions
{
public static List<DirectoryInfo> GetSubFolders(this DirectoryInfo rootFolder)
{
if (rootFolder == null)
{
throw new ArgumentException("Root-Folder must not be null!", "rootFolder");
}
List<DirectoryInfo> subFolders = new List<DirectoryInfo>();
AddSubFoldersRecursively(rootFolder, ref subFolders);
return subFolders;
}
private static void AddSubFoldersRecursively(DirectoryInfo rootFolder, ref List<DirectoryInfo> allFolders)
{
try
{
allFolders.Add(rootFolder);
foreach (DirectoryInfo subFolder in rootFolder.GetDirectories())
{
AddSubFoldersRecursively(subFolder, ref allFolders);
}
}
catch (UnauthorizedAccessException exUnauthorized)
{
// go on
}
catch (DirectoryNotFoundException exNotFound)
{
// go on
}
catch (Exception ex)
{
throw;
}
}
}
}
Если кто-то заинтересован в версии VB.NET:
Public Module DirectoryExtensions
<Runtime.CompilerServices.Extension()>
Public Function GetSubFolders(ByVal rootFolder As DirectoryInfo) As List(Of DirectoryInfo)
If rootFolder Is Nothing Then
Throw New ArgumentException("Root-Folder must not be null!", "rootFolder")
End If
Dim subFolders As New List(Of DirectoryInfo)
AddSubFoldersRecursively(rootFolder, subFolders)
Return subFolders
End Function
Private Sub AddSubFoldersRecursively(rootFolder As DirectoryInfo, ByRef allFolders As List(Of DirectoryInfo))
Try
allFolders.Add(rootFolder)
For Each subFolder In rootFolder.GetDirectories
AddSubFoldersRecursively(subFolder, allFolders)
Next
Catch exUnauthorized As UnauthorizedAccessException
' go on '
Catch exNotFound As DirectoryNotFoundException
' go on '
Catch ex As Exception
Throw
End Try
End Sub
End Module
Проверено с:
Dim result = Me.FolderBrowserDialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
Dim rootPath = Me.FolderBrowserDialog1.SelectedPath
Dim rootFolder = New DirectoryInfo(rootPath)
Dim query = From folder In rootFolder.GetSubFolders()
Select folder.FullName
If query.Any Then
Me.ListBox1.Items.AddRange(query.ToArray)
End If
End If