Alex Rivera | Logout

How do I determine a file's content type in .NET?

Asked 2009-03-27T19:38:30.493
14

My WPF application gets a file from the user with 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

And my ASP.NET MVC application serves it up for download at a web site with FileStreamResult()...

Public Class ZackFileController
    Inherits System.Web.Mvc.Controller

    Function Display(ByVal id As Guid) As FileStreamResult
    
Edit
Report

1 Answer

2

It looks like you still have the filename when you go to set the content type. You could pick the correct mime type for the file extension, or default to something like "application/base64".

Assuming the person downloading it will be using a web browser, try to stick to the common ones: MIME Types Known By IE

answered 2009-03-27T19:54:12.093

Your Answer