当前位置:  开发笔记 > 编程语言 > 正文

如何在.NET中确定文件的内容类型?

如何解决《如何在.NET中确定文件的内容类型?》经验,为你挑选了2个好方法。

我的WPF应用程序从Microsoft.Win32.OpenFileDialog()获取用户的文件...

Private Sub ButtonUpload_Click(...)
    Dim FileOpenStream As Stream = Nothing
    Dim FileBox As New Microsoft.Win32.OpenFileDialog()
    FileBox.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    FileBox.Filter = "Pictures (*.jpg;*.jpeg;*.gif;*.png)|*.jpg;*.jpeg;*.gif;*.png|" & _
                     "Documents (*.pdf;*.doc;*.docx;)|*.pdf;*.doc;*.docx;|" & _
                     "All Files (*.*)|*.*"
    FileBox.FilterIndex = 1
    FileBox.Multiselect = False
    Dim FileSelected As Nullable(Of Boolean) = FileBox.ShowDialog(Me)
    If FileSelected IsNot Nothing AndAlso FileSelected.Value = True Then
        Try
            FileOpenStream = FileBox.OpenFile()
            If (FileOpenStream IsNot Nothing) Then
                Dim ByteArray As Byte()
                Using br As New BinaryReader(FileOpenStream)
                    ByteArray = br.ReadBytes(FileOpenStream.Length)
                End Using
                Dim z As New ZackFile
                z.Id = Guid.NewGuid
                z.FileData = ByteArray
                z.FileSize = CInt(ByteArray.Length)
                z.FileName = FileBox.FileName.Split("\").Last
                z.DateAdded = Now
                db.AddToZackFile(z)
                db.SaveChanges()
            End If
        Catch Ex As Exception
            MessageBox.Show("Cannot read file from disk. " & Ex.Message, "Fail", MessageBoxButton.OK, MessageBoxImage.Error)
        Finally
            If (FileOpenStream IsNot Nothing) Then
                FileOpenStream.Close()
            End If
        End Try
    End If
End Sub

我的ASP.NET MVC应用程序使用FileStreamResult()在网站上下载...

Public Class ZackFileController
    Inherits System.Web.Mvc.Controller

    Function Display(ByVal id As Guid) As FileStreamResult
        Dim db As New EfrDotOrgEntities
        Dim Model As ZackFile = (From z As ZackFile In db.ZackFile _
                                Where z.Id = id _
                                Select z).First
        Dim ByteArray As Byte() = Model.ImageData
        Dim FileStream As System.IO.MemoryStream = New System.IO.MemoryStream(ByteArray)
        Dim ContentType As String = ?????
        Dim f As New FileStreamResult(FileStream, ContentType)
        f.FileDownloadName = Model.FileName
        Return f
    End Function

End Class

但是FileStreamResult()需要一个内容类型字符串.我如何知道我的文件的正确内容类型?



1> 小智..:

.NET 4.5中有一个MimeMapping类

http://msdn.microsoft.com/en-us/library/system.web.mimemapping.aspx



2> Zack Peterso..:

我用ContentType列替换了数据库表中的FileExtension列.

我上传文件时填充它.

Private Sub ButtonUpload_Click(...)
    ...
    Dim FileExtension As String = "." + FileBox.FileName.Split(".").Last.ToLower
    z.ContentType = ContentType(FileExtension)
    ...
End Sub

我用这个函数确定内容类型:

Function ContentType(ByVal FileExtension As String) As String
    Dim d As New Dictionary(Of String, String)
    'Images'
    d.Add(".bmp", "image/bmp")
    d.Add(".gif", "image/gif")
    d.Add(".jpeg", "image/jpeg")
    d.Add(".jpg", "image/jpeg")
    d.Add(".png", "image/png")
    d.Add(".tif", "image/tiff")
    d.Add(".tiff", "image/tiff")
    'Documents'
    d.Add(".doc", "application/msword")
    d.Add(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
    d.Add(".pdf", "application/pdf")
    'Slideshows'
    d.Add(".ppt", "application/vnd.ms-powerpoint")
    d.Add(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation")
    'Data'
    d.Add(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    d.Add(".xls", "application/vnd.ms-excel")
    d.Add(".csv", "text/csv")
    d.Add(".xml", "text/xml")
    d.Add(".txt", "text/plain")
    'Compressed Folders'
    d.Add(".zip", "application/zip")
    'Audio'
    d.Add(".ogg", "application/ogg")
    d.Add(".mp3", "audio/mpeg")
    d.Add(".wma", "audio/x-ms-wma")
    d.Add(".wav", "audio/x-wav")
    'Video'
    d.Add(".wmv", "audio/x-ms-wmv")
    d.Add(".swf", "application/x-shockwave-flash")
    d.Add(".avi", "video/avi")
    d.Add(".mp4", "video/mp4")
    d.Add(".mpeg", "video/mpeg")
    d.Add(".mpg", "video/mpeg")
    d.Add(".qt", "video/quicktime")
    Return d(FileExtension)
End Function

这有效,但似乎不够优雅.


每次调用`ContentType`时,您可能应该使用switch语句而不是构建新的字典.此外,还有一个`Path.GetExtension`方法,因此您不必手动拆分文件名.
推荐阅读
贾志军
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有