问题描述
我遇到了此代码的问题,即将目录拉入列表。它在我的机器上运行良好,它们都存在,但是当我在另一台没有其中一个的机器上运行时,它无法加载列表并给出未处理的异常(System.IO.DirectoryNotFoundException:找不到路径的一部分'C:\阿勒顿..)。我需要检查所有目录,但如果它们不存在,我只需要跳过并查找下一个。提前致谢,我是新手,很抱歉,如果这是我忽略的简单事情。
Private Sub getjobs(sender As Object,e As EventArgs) 处理 MyBase.Load
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Compass\1.0\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Compass\1.5.1\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Compass\1.6.4\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Compass\1.6.5\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Bactalk\3.0\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Bactalk\3.1\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
'Console.WriteLine(Dir)
Next
End Sub
解决方法
首先,我猜你的代码是visual basic而不是C#,所以你可能想用“visual basic”替换“C#”标签以获得比这更好的答案,因为我从来没有主动使用过。
关于例外:
如果指定的路径无效,“Directory.GetDirectories”方法会抛出“DirectoryNotFoundException”(见https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getdirectories?view=netframework-4.8)。
要忽略它,您需要捕获它并且在 catch 块中什么都不做。请参阅 https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement 了解更多信息。
示例:
Try
For Each Dir As String In Directory.GetDirectories("C:\Alerton\Compass\1.0\ATSINC")
ListBox1.Items.Add(Dir & "\ddc")
Next
Catch ex As DirectoryNotFoundException
' do nothing
End Try