Trying to compile directories, but skip if directorie isn't present and search for next

27 views Asked by At

I am running into an issue with this code that is pulling directories into a list. It works fine on my machine they all exist, however when I run on another that doesn't have one of them it fails to load the list and gives an unhandled exception (System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Alerton..). I need all the directories to be checked, but if they are not present I simply need to skip and look for the next. Thanks in advance, I am new at this so sorry if this is a simple thing I am overlooking.

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
1

There are 1 answers

1
d-v-lop-r On

First of all I guess your code is visual basic and not C# so you may want to replace the 'C#' tag with 'visual basic' to get some better answers than this as I never used that actively.

Regarding the exception:

The "Directory.GetDirectories" method throws the "DirectoryNotFoundException" if the specified path is invalid (see https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.getdirectories?view=netframework-4.8).

To ignore this you need to catch it and do nothing in the catch block. Please see https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement for further information.

Example:

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