更好的检查扩展的方式

时间:2012-11-30 21:00:59

标签: arrays vb.net file-extension

嘿,我有以下代码:

Dim validFileTypes As String() = {".bmp", ".gif", ".png", ".jpg", ".jpeg", ".tif"}

For x = 0 To NumberOfBoxes - 1
        With myTxtData(x)
            If Not Fields("customField" & z).Value.Equals(DBNull.Value) Then
                If InStr(Fields("customField" & z).Value, "@") <> 0 Then
                    'Lower case the email address
                    .Text = StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase)
                ElseIf InStr(StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase), ".jpg") <> 0 Then
                    'It contains an image!
                Else
                    .Text = StrConv(Fields("customField" & z).Value, VbStrConv.ProperCase)
                End If
  etc etc.....

而不是我这样检查:

ElseIf InStr(StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase), ".jpg") <> 0 
OR InStr(StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase), ".png") <> 0 
OR InStr(StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase), ".gif") <> 0 
...etc...

如何使用我定义的 validFileTypes 来执行相同操作,但代码更少?

1 个答案:

答案 0 :(得分:1)

您可能需要添加一些代码,但这应该让您走上正确的道路:

Dim isImage as Boolean = False

For each validFileType in validFileTypes
     If InStr(StrConv(Fields("customField" & z).Value, VbStrConv.Lowercase), validFileType) <> 0 Then
         isImage = True
     End If
Next