我在Visual Basic中使用GetFileSystemEntries()来获取驱动器的完整结构,我使用了我在MSDN中找到的异常但是我无法弄清楚如何只传递给我的目录错误并将其他人保存在我的数组中。
这是我的代码:
Dim array()
Try
array = System.IO.Directory.GetFileSystemEntries("C:\", "*", System.IO.SearchOption.AllDirectories)
For Each x As System.String In array
list_Drives.Items.Add(x)
Next
Catch exp As UnauthorizedAccessException
System.Console.WriteLine("I don't have permission here")
Catch exp As ArgumentNullException
System.Console.WriteLine("Path is a null reference.")
Catch exp As System.Security.SecurityException
System.Console.WriteLine("The caller does not have the " + _
"required permission.")
Catch exp As ArgumentException
System.Console.WriteLine("Path is an empty string, " + _
"contains only white spaces, " + _
"or contains invalid characters.")
Catch exp As System.IO.DirectoryNotFoundException
System.Console.WriteLine("The path encapsulated in the " + _
"Directory object does not exist.")
End Try
谢谢
答案 0 :(得分:0)
System.IO.Directory.GetFileSystemEntries
抛出异常,所以当发生这种情况时,for循环不执行,并且没有“其他”目录(除非你还没有显示其他代码)。
如果要以递归方式枚举从根开始的目录,那么最好编写自己的递归代码。这将允许您跳过异常(即,您不允许枚举的目录)。
具有GetFileSystemEntries
参数的Uinsg System.IO.SearchOption.AllDirectories
更适合遍历由应用程序创建的目录结构。否则,当遍历任意目录时,很可能会遇到访问问题。此外,如果目录结构中存在创建循环Microsoft says you'll end up in an infinite loop的链接。
如果您创建自己的遍历算法,则可以避免这些问题。或者,如果您环顾四周,您可能会找到一个已经为您完成此操作的库。