Is there any built in function that returns the content type based on the file extension?
Not that I know of. But you can use this code:
using Microsoft.Win32;
RegistryKey key = Registry.ClassesRoot.OpenSubKey(extension);
string contentType = key.GetValue("Content Type").ToString();
You'll need to add extra code for error handling.
Note: The extension needs to be prefixed by a dot, like in .txt
.
Since .Net Framework 4.5 there is a class System.Web.MimeMapping
which has a complete library of mime types with methods to get the requested mime type.
See: http://msdn.microsoft.com/en-us/library/system.web.mimemapping(v=vs.110).aspx
or for the implementation of GetMimeMapping
: https://referencesource.microsoft.com/#System.Web/MimeMapping.cs
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