Detectando MIME types com C#

Normalmente em alguns aplicativos temos a necessidade de detectar o MIME type de determinados arquivos. Segue abaixo uma classe MimeHelper que pode nos ajudar nessa tarefa, uma nota interessante foi a utilização de Reflection e a classe MimeMapping.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;

namespace WebHelpers
{
    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("Não foi possível encontrar o tipo MimeMapping.");

            _getMimeMappingMethodInfo = mimeMappingType.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

            if (_getMimeMappingMethodInfo == null)
            throw new SystemException("Não foi possível encontrar o método GetMimeMapping.");

            if (_getMimeMappingMethodInfo.ReturnType != typeof(string))
            throw new SystemException("Método GetMimeMapping retornou um tipo inválido.");

            if (_getMimeMappingMethodInfo.GetParameters().Length != 1 && _getMimeMappingMethodInfo.GetParameters()[0].ParameterType != typeof(string))
            throw new SystemException("Método GetMimeMapping possui parâmentros inválidos.");
        }

        public static string GetMimeType(string filename)
        {
            lock (_locker)
                return (string)_getMimeMappingMethodInfo.Invoke(_mimeMapping, new object[] { filename });
        }
    }
}

Testando:


using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebHelpers;

namespace WebHelpers.Test
{
    [TestClass()]
    public class MimeHelperTest
    {
        /// <summary>
        /// A test for GetMimeType
        /// </summary>
        [TestMethod()]
        public void GetMimeTypeTextPlainTest()
        {
            string filename = Path.Combine(@"C:\Visual Studio 2008\Projects\WebHelpers\WebHelpers.Test\", "Files\\test.txt");
            string expected = "text/plain";
            string actual;
            actual = MimeHelper.GetMimeType(filename);
            Assert.AreEqual(expected, actual);
        }

        [TestMethod()]
        public void GetMimeTypeImageJpegTest()
        {
            string filename = Path.Combine(@"C:\Visual Studio 2008\Projects\WebHelpers\WebHelpers.Test\", "Files\\test.JpG");
            string expected = "image/jpeg";
            string actual;
            actual = MimeHelper.GetMimeType(filename);
            Assert.AreEqual(expected, actual);
        }

        [TestMethod()]
        public void GetMimeTypeApplicationOctetStreamTest()
        {
            string filename = Path.Combine(@"C:\Visual Studio 2008\Projects\WebHelpers\WebHelpers.Test\", "Files\\test.mp4");
            string expected = "application/octet-stream";
            string actual;
            actual = MimeHelper.GetMimeType(filename);
            Assert.AreEqual(expected, actual);
        }
    }
}