Loading ...

.NET: Get mimetype/contenttype from file name/extension | CodeAsp.Net

.NET: Get mimetype/contenttype from file name/extension

3.82 
 /5
3.82 (1votes)

In order to get mimetype/contenttype from file name/extension you need to make use of "System.Web.MimeMapping" assembly. Below is the helper class to get the mime type:

using System;
using System.Reflection;
using System.Web;

namespace MyNamespace
{
    public static class MimeHelper
    {
        private static readonly object Locker = new object();
        private static object mimeMapping;
        private static readonly MethodInfo GetMimeMappingMethodInfo;
        static MimeHelper()
        {
            Type mimeMappingType = Assembly.GetAssembly(typeof(HttpRuntime)).GetType("System.Web.MimeMapping");
            if (mimeMappingType == null)
                throw new SystemException("Couldnt find MimeMapping type");            
            GetMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", 
                BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
            if (GetMimeMappingMethodInfo == null)
                throw new SystemException("Couldnt find GetMimeMapping method");
            if (GetMimeMappingMethodInfo.ReturnType != typeof(string))
                throw new SystemException("GetMimeMapping method has invalid return type");
            if (GetMimeMappingMethodInfo.GetParameters().Length != 1 
                && GetMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
                throw new SystemException("GetMimeMapping method has invalid parameters");
        }

        public static string GetMimeType(string filename)
        {
            lock (Locker)
                return (string)GetMimeMappingMethodInfo.Invoke(mimeMapping, 
                    new object[] { filename });
        }

    }
}  

Usage:

            string[] files = new string[5];
            files[0] = "C:\\test.txt";
            files[1] = "C:\\test.jpg";
            files[2] = "C:\\test.mp3";
            files[3] = "C:\\test.mp4";
            files[4] = "C:\\test.srt";

            foreach (string file in files)
            {
                string contentType = MimeHelper.GetMimeType(file);
                Response.Write(contentType);
                Response.Write("<br/>");
            }


Output:

text/plain
image/jpeg
audio/mpeg
application/octet-stream
application/octet-stream


Comments (no comments yet)

Top Posts