Search code examples
vb.netstringcomparecontainsarrays

check if string contains any of the elements of a stringarray (vb net)


I´ve got a little problem. At the end of a programm it should delete a folder.

In ordern to deny deletion of a folder, which directory contains a certain word, I wanted to check if a string (the directory.fullname.tostring) contains any of the elements which are stored in a string array. The string array contains strings stating the exception words.

This is how far I got and I know that the solution is the other way round than stated here:

If Not stackarray.Contains(dir.FullName.ToString) Then

                Try
                    dir.Delete()
                    sw.WriteLine("deleting directory " + dir.FullName, True)
                    deldir = deldir + 1
                Catch e As Exception
                    'write to log
                    sw.WriteLine("cannot delete directory " + dir.ToString + "because there are still files in there", True)
                    numbererror = numbererror + 1
                End Try
            Else
                sw.WriteLine("cannot delete directory " + dir.ToString + "because it is one of the exception directories", True)
            End If

Solution

  • Instead of checking to see if the array contains the full path, do it the other way around. Loop through all the items in the array and check if the path contains each one, for instance:

    Dim isException As Boolean = False
    For Each i As String In stackarray
        If dir.FullName.ToString().IndexOf(i) <> -1 Then
            isException = True
            Exit For
        End If
    Next
    If isException Then
        ' ...
    End If
    

    Or, if you want to be more fancy, you can use the Array.Exists method to do it with less lines of code, like this:

    If Array.Exists(stackarray, Function(x) dir.FullName.ToString().IndexOf(x) <> -1) Then
        ' ...
    End If