Dot-Net

如何在 .NET 中確定文件的內容類型?

  • November 21, 2015

我的 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() 需要一個內容類型字元串。我如何知道文件的正確內容類型?

我基於 Zacks 響應創建了一個 C# 助手類。

/// <summary>
/// Helps with Mime Types
/// </summary>
public static class MimeTypesHelper
{
   /// <summary>
   /// Returns the content type based on the given file extension
   /// </summary>
   public static string GetContentType(string fileExtension)
   {
       var mimeTypes = new Dictionary<String, String>
           {
               {".bmp", "image/bmp"},
               {".gif", "image/gif"},
               {".jpeg", "image/jpeg"},
               {".jpg", "image/jpeg"},
               {".png", "image/png"},
               {".tif", "image/tiff"},
               {".tiff", "image/tiff"},
               {".doc", "application/msword"},
               {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
               {".pdf", "application/pdf"},
               {".ppt", "application/vnd.ms-powerpoint"},
               {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
               {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
               {".xls", "application/vnd.ms-excel"},
               {".csv", "text/csv"},
               {".xml", "text/xml"},
               {".txt", "text/plain"},
               {".zip", "application/zip"},
               {".ogg", "application/ogg"},
               {".mp3", "audio/mpeg"},
               {".wma", "audio/x-ms-wma"},
               {".wav", "audio/x-wav"},
               {".wmv", "audio/x-ms-wmv"},
               {".swf", "application/x-shockwave-flash"},
               {".avi", "video/avi"},
               {".mp4", "video/mp4"},
               {".mpeg", "video/mpeg"},
               {".mpg", "video/mpeg"},
               {".qt", "video/quicktime"}
           };

       // if the file type is not recognized, return "application/octet-stream" so the browser will simply download it
       return mimeTypes.ContainsKey(fileExtension) ? mimeTypes[fileExtension] : "application/octet-stream";
   }
}

當然,您可能希望mimeTypes為將來的查詢保持活動狀態。這只是一個起點。

.NET 4.5 中有一個 MimeMapping 類

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

引用自:https://stackoverflow.com/questions/691212