user4743021
user4743021

Reputation:

Using If statement to verify if string value is in an array of strings

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

Upvotes: 1

Views: 396

Answers (2)

video.baba
video.baba

Reputation: 884

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

Upvotes: 2

alekini
alekini

Reputation: 11

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)

Upvotes: 0

Related Questions