1

I have a string and an array of strings. I was wondering if it is possible to use an If statement in order to return a boolean value if the string contains a value from the array.

The code below doesn't work properly. Contains can only take in one value as far as I can see. Is there a better way to do this without having to use a loop?

Dim FilePath As String = "C:\Users\Downloads\Test.jpg"
Dim GetExtension As String = FilePath.Substring(FilePath.Length - 3)
Dim FileExtensionArray() As String = {".png", ".jpg", ".tif"}

If GetExtension.Contains(FileExtension) = True Then
   ' Code
Else
   ' Code
End If
3

2 Answers 2

2

Just a couple of things to note about your code:

Dim GetExtension As String = FilePath.Substring(FilePath.Length - 3)
Dim FileExtensionArray() As String = {".png", ".jpg", ".tif"}

GetExtension now contains jpg but your arrays are .jpg. There's some built-in help already available for file extensions:

IO.Path.GetExtension(FilePath)

Lastly, your If .... Then test is the wrong way round. With a couple of simple adjustments I'd use this:

    Dim FilePath As String = "C:\Users\Downloads\Test.jpg"
    Dim FilePathExtension As String = IO.Path.GetExtension(FilePath)
    Dim FileExtensionArray As String() = {".png", ".jpg", ".tif"}

    If FileExtensionArray.Contains(FilePathExtension) Then
        'yes
    Else
        'no
    End If
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you could convert FileExtensionArray in a string with the function Join:

 GetExtensionsJoin= String.Join( "-", FileExtensionArray)

After that, you could use the method "contains" to check if string contains the extension.

 GetExtensionsJoin.contains(GetExtension)

1 Comment

This will return true for a wrong reasons. For example when file extension is a substring of any of allowed extensions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.