I am looking for a simple way to get a mime type where the file extension is incorrect or not given, something similar to this question only in .Net.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
If someone was up for it they could port the excellent perl module File::Type to .NET. In the code is a set of file header magic number look ups for each file type or regex matches.
Here's a .NET file type detecting library http://filetypedetective.codeplex.com/ but it only detects a smallish number of files at the moment.
I use an hybrid solution:
In Urlmon.dll, there's a function called
FindMimeFromData
.From the documentation
So, read the first (up to) 256 bytes from the file and pass it to
FindMimeFromData
.IIS 7 or more
Use this code, but you need to be the admin on the server
This answer is a copy of the author's answer (Richard Gourlay), but improved to solve issues on IIS 8 / win2012 (where function would cause app pool to crash), based on Rohland's comment pointing to http://www.pinvoke.net/default.aspx/urlmon.findmimefromdata
...
If you're using .NET Framework 4.5 or above, there is a now a MimeMapping.GetMimeMapping(filename) method that will return a string with the correct Mime mapping for the passed filename. Note that this uses the file extension, not data in the file itself.
Documentation is at http://msdn.microsoft.com/en-us/library/system.web.mimemapping.getmimemapping