-1

I have been trying to get the Mime type form the file where i dont really know the File Type of the file. I know that there is a same questions here

but this is not complete as i have to support .dwg (CAD files) it is basically to use with Solr Search Engine. So looking for a way where i can automatically read the Mime Type from the stream or signatures of the file.

Community
  • 1
  • 1
John Sheedy
  • 287
  • 1
  • 8
  • 26

3 Answers3

1

There's a non-public method that .NET uses under the hood to do this. I have devised a way to steal the functionality and make it public:

/// <summary>
/// Exposes the Mime Mapping method that Microsoft hid from us.
/// </summary>
public static class MimeMappingStealer
{
    // The get mime mapping method
    private static readonly Func<string, string> _getMimeMappingMethod = null;

    /// <summary>
    /// Static constructor sets up reflection.
    /// </summary>
    static MimeMappingStealer()
    {
        // Load hidden mime mapping class and method from System.Web
        var assembly = Assembly.GetAssembly(typeof(HttpApplication));
        Type mimeMappingType = assembly.GetType("System.Web.MimeMapping");
        _getMimeMappingMethod = (Func<string, string>)Delegate.CreateDelegate(typeof(Func<string, string>), mimeMappingType.GetMethod("GetMimeMapping", 
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.FlattenHierarchy));
    }

    /// <summary>
    /// Exposes the hidden Mime mapping method.
    /// </summary>
    /// <param name="fileName">The file name.</param>
    /// <returns>The mime mapping.</returns>
    public static string GetMimeMapping(string fileName)
    {
        return _getMimeMappingMethod(fileName);
    }
}

To use:

var fileName1 = "whatever.js";
var fileName2 = "somefile.css";
var fileName3 = "myfile.html";

MimeMappingStealer.GetMimeMapping(fileName1) // application/x-javascript    
MimeMappingStealer.GetMimeMapping(fileName2) // text/css
MimeMappingStealer.GetMimeMapping(fileName3) // text/html

This code from my blog: http://www.haneycodes.net/a-better-mime-mapping-stealer/

Haney
  • 32,775
  • 8
  • 59
  • 68
0

You can se Path class in System.IO namespace with Path.GetExtension( "strfilename.dwg") and you will get the extension .dwg ...just to be sure you can make it .ToLower() and compare it with ".dwg" and proceed with your processing.

If you are using FileUpload control is asp.net there is a way to find out mime type by using FileUpload1.PostedFile.ContentType . Where FileUpload1 is the name of the control, PostedFile and ContentType are Properties and ContentType denotes the Mime type.

Checkout the FileUpload control on msdn for more.

Bharat
  • 152
  • 1
  • 9
0

System.Web.MimeMapping will not work for the files without the extension. It will default to application/octet-stream