I am trying to determine dynamically the content/type of a input file. If I would be in a windows application I could write code like this (from this blog)
private string GetContentType(string fileName) { string contentType = "application/octetstream"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (registryKey != null && registryKey.GetValue("Content Type") != null) contentType = registryKey.GetValue("Content Type").ToString(); return contentType; }
What other methods are more suitable for an MVC application?
I would like to use the param within the Controller.File(...)
method that receive a filepath and a contentype.
If you are on a linux/unix like system you can use the file command to determine the file type. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file type to be printed.
MIME stands for "Multipurpose Internet Mail Extensions." It is a standard way of classifying file types on the Internet. By specifying a MIME type, application can easily identify the type of file and can extract more information and attributes about a file.
MIME types are defined by three attributes: language (lang), encoding (enc), and content-type (type). At least one of these attributes must be present for each type. The most commonly used attribute is type. The server frequently considers the type when deciding how to generate the response to the client.
We can use the net/http package to find the content type, or mime type, of a file. To do this, we open the file and read the first 512 bytes (as the DetectContentType () function only uses the first 512 bytes, there’s no point in doing more than needed).
There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file type to be printed. If you're on a Windows machine it is common to use the file extension like you showed in your code.
There are a number of ways/techniques to do that, but – for the sake of simplicity – we will put them down to two: looking them up within the Windows Registry or relying to static, hard-coded MIME type lists. We won’t consider anything that involves querying an external service, as we do want an efficient way to deal with such issue.
/// Retrieves the MimeType bound to the given filename or extension by looking into the Windows Registry entries. /// NOTE: This method supports only the MimeTypes registered in the server OS / Windows installation.
In .Net 4.5 you can use MimeMapping.GetMimeMapping
:
string contentType = MimeMapping.GetMimeMapping("someFileName.pdf") // contentType = "application/pdf"
More information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With