【问题标题】:Trying to compile directories, but skip if directorie isn't present and search for next尝试编译目录,但如果目录不存在则跳过并搜索下一个
【发布时间】:2021-04-21 17:11:39
【问题描述】:

我遇到了将目录拉入列表的代码的问题。它在我的机器上运行良好,它们都存在,但是当我在另一个没有它们的机器上运行时,它无法加载列表并给出未处理的异常(System.IO.DirectoryNotFoundException:找不到路径的一部分'C:\Alerton..)。我需要检查所有目录,但如果它们不存在,我只需跳过并查找下一个。在此先感谢,如果这是我忽略的一件简单的事情,我很抱歉。

Private Sub getjobs(sender As Object, e As EventArgs) Handles 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

【问题讨论】:

    标签: c# getdirectories


    【解决方案1】:

    首先我猜你的代码是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    
    

    【讨论】:

    • 谢谢你,我会试一试并做一些阅读。另外,是的,您在 Visual Basic 上是正确的,我会更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2015-08-12
    • 2016-12-25
    • 2018-08-01
    相关资源
    最近更新 更多