我正在尝试在 Visual Studio 2012 的给定路径中创建所有目录及其子目录的列表。
自从我接触visual basic以来已经很长时间了。我希望有人可以为这项任务展示一种简单的方法。
非常感谢任何形式的帮助。:)
我正在尝试在 Visual Studio 2012 的给定路径中创建所有目录及其子目录的列表。
自从我接触visual basic以来已经很长时间了。我希望有人可以为这项任务展示一种简单的方法。
非常感谢任何形式的帮助。:)
在 System.IO 命名空间中
Directory.GetDirectories(string, string, SearchOptions)
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
Dim path as string ="c:\DirectoryTest"
Dim result = Directory.EnumerateDirectories(path, "*", System.IO.SearchOption.AllDirectories)
此递归方法将从给定路径获取所有目录及其子目录:
选项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