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
I came across the same issue and eventually opted for my own flavour of Kirk Baucom's solution, found here.
It seems to me that this is an opportunity for someone to write an online look-up service.
Anyway, Hope it helps.
This class use previous answers to try in 3 different ways: harcoded based on extension, FindMimeFromData API and using registry.
I think the right answer is a combination of Steve Morgan's and Serguei's answers. That's how Internet Explorer does it. The pinvoke call to
FindMimeFromData
works for only 26 hard-coded mime types. Also, it will give ambigous mime types (such astext/plain
orapplication/octet-stream
) even though there may exist a more specific, more appropriate mime type. If it fails to give a good mime type, you can go to the registry for a more specific mime type. The server registry could have more up-to-date mime types.Refer to: http://msdn.microsoft.com/en-us/library/ms775147(VS.85).aspx
I did use urlmon.dll in the end. I thought there would be an easier way but this works. I include the code to help anyone else and allow me to find it again if I need it.
...
@Steve Morgan and @Richard Gourlay this is a great solution, thank you for that. One small drawback is that when the number of bytes in a file is 255 or below, the mime type will sometimes yield "application/octet-stream", which is slightly inaccurate for files which would be expected to yield "text/plain". I have updated your original method to account for this situation as follows:
If the number of bytes in the file is less than or equal to 255 and the deduced mime type is "application/octet-stream", then create a new byte array that consists of the original file bytes repeated n-times until the total number of bytes is >= 256. Then re-check the mime-type on that new byte array.
Modified method:
I ended up using Winista MimeDetector from Netomatix. The sources can be downloaded for free after you created an account: http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx
This is part of another question answered here: Alternative to FindMimeFromData method in Urlmon.dll one which has more MIME types The best solution to this problem in my opinion.