获取基于扩展名vb.net的文件类型

时间:2014-09-03 05:48:44

标签: vb.net

我需要根据上传图像的文件类型显示每个组的默认图像。那是

我正在file Groups作为

  • 图片 {".jpeg", ".jpg", ".png", ".bmp", ".gif", ".tif"}
  • {li> 文档 {".doc", ".docx", ".txt", ".htm", ".html", ".xml", ".xaml", ".css"}
  • excel {".xls", ".xlsx", ".xlt", ".xla"}
  • pdf ".pdf"
  • 压缩 {".7z", ".APK", ".BAT", ".rar", ".dll", ".jar", ".zip"}

如果输入扩展名为" .xls" ,那么我需要输出为"excel"

我曾尝试使用Select Case

  Select Case search
        Case ".docx"
            extensionType = "document"
        Case ".doc"
            extensionType = "document"
        Case ".txt"
            extensionType = "document"
         ---------
    End Select

但代码很冗长我怎么能缩短这个?

2 个答案:

答案 0 :(得分:2)

您可以为每一行指定多个CASE条件:

Select Case search
    Case ".doc", ".docx", ".txt"
        extensionType = "document"
    Case ".jpeg", ".jpg", ".png", ".bmp"
        extensionType = "picture"
End Select

或者您也可以使用dict,但扩展名为关键字:

Dim map As New Dictionary(Of String, String)
map.Add(".doc", "document")
map.Add(".docx", "document")
map.Add(".jpg", "picture")
map.Add(".png", "picture")
Console.WriteLine(map(".docx"))

答案 1 :(得分:1)

您可以使用Dictionary概念进行此类操作:请考虑以下代码

Private Sub getfileType_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles getfileType.Click
    Dim array As String()
    Dim extensionType As String
    Dim dics As New Dictionary(Of String, String()) From { _
    {"picture", New String() {".jpeg", ".jpg", ".png", ".bmp", ".gif", ".tif"}}, _
    {"document", New String() {".doc", ".docx", ".txt", ".htm", ".html", ".xml", ".xaml", ".css"}}, _
    {"excel", New String() {".xls", ".xlsx", ".xlt", ".xla"}}, _
    {"pdf", New String() {".pdf"}}, _
    {"zip", New String() {".7z", ".APK", ".BAT", ".rar", ".dll", ".jar", ".zip"}}, _
    {"ppt", New String() {".ppt", ".pos", ".pps"}}}
    Dim pair As KeyValuePair(Of String, String())
    For Each pair In dics
        If attachmentType(pair.Key, pair.Value, ".APK") = True Then
            extensionType = pair.Key
            Exit For
        End If
    Next
    MsgBox("File Type is :" & extensionType)
End Sub

Public Function attachmentType(ByVal input As String, ByVal array() As String, ByVal search As String) As Boolean
    Dim temp As Integer = 0
    For i As Integer = 0 To array.Length - 1
        If array(i) = search Then temp = 1
    Next
    If temp = 1 Then
        attachmentType = True
    Else
        attachmentType = False
    End If
End Function