我正在尝试在visual studio 2012中创建给定路径中所有目录及其子目录的列表。
自从我接触到visual basic以来已经很长时间了。我希望有人可以为这项任务展示一个简单的方法。
非常感谢任何形式的帮助。 :)
答案 0 :(得分:3)
在System.IO名称空间
中 Directory.GetDirectories(string, string, SearchOptions)
来自MSDN
的一个很好的例子 Dim dirs As String() = Directory.GetDirectories("c:\", "*.*", SearchOption.AllDirectories)
Console.WriteLine("The number of directories starting with p is {0}.", dirs.Length)
Dim dir As String
For Each dir In dirs
Console.WriteLine(dir)
Next
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
但是请记住,某些目录可能具有特定的访问权限,并且您的代码可能会因IOException而失败。 (对于系统目录尤其如此)
另一种选择是使用Directory.EnumerateDirectories,当你使用许多目录并且不需要填充名称的字符串数组时,这是最好的。
EnumerateDirectories立即启动而无需等待填充数组,在代码循环遍历枚举的情况下非常有用
For Each dirName in Directory.EnumerateDirectories("C:\", "p*", SearchOptions.AllDirectories)
..... do something with the directory here ....
Next
答案 1 :(得分:1)
Dim path as string ="c:\DirectoryTest"
Dim result = Directory.EnumerateDirectories(path, "*", System.IO.SearchOption.AllDirectories)
答案 2 :(得分:0)
这种递归方法将获得所有目录&它来自给定路径的子目录:
选项1#
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim subdirectoryEntries As String() =
Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
选项2#
Module Module1
Sub Main()
Try
Dim dirPath As String = "c:\\myDirctory"
Dim dirs As List(Of String) = New List(Of String)(Directory.EnumerateDirectories(dirPath))
For Each folder In dirs
Console.WriteLine("{0}", folder.Substring(folder.LastIndexOf("\") + 1))
Next
Console.WriteLine("{0} directories found.", dirs.Count)
Catch UAEx As UnauthorizedAccessException
Console.WriteLine(UAEx.Message)
Catch PathEx As PathTooLongException
Console.WriteLine(PathEx.Message)
End Try
End Sub
End Module
您可以参考MSDN了解更多详情:
http://msdn.microsoft.com/en-us/library/c1sez4sc.aspx
http://msdn.microsoft.com/en-us/library/dd383304.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2