Detecting MIME Type of a file - from its inputstream
While uploading a file, identifying the MIME type would be a required operation for certain programmers who would like to save the file as a binary stream in their Database.
Below given code helps us in identifying the MIME type of any uploaded file using a third party Assembly Winista.MimeDetect.dll. It is free to use and could be downloaded from this URL[http://www.netomatix.com/Products/DocumentManagement/MimeDetector.aspx]
1. Add the XML file, mime-types.xml, in your application root directory
2. Add the DLL file, Winista.MimeDetect.dll, to your Bin folder
3. Add the below given code in the BL logic
using Winista.Mime;
public MimeType GetMimeType(Stream objInputStream)
{
MimeType objMimeType = null;
if (objInputStream!= null)
{
string strMimeXMLPath = HttpContext.Current.Server.MapPath("~/mime-types.xml");
MimeTypes g_MimeTypes = new MimeTypes(strMimeXMLPath);
sbyte[] sfileData = null;
byte[] objData = new byte[objInputStream.Length];
objInputStream.Read(objData , 0, (Int32) objInputStream.Length);
sfileData = Winista.Mime.SupportUtil.ToSByteArray(objData);
objMimeType = g_MimeTypes.GetMimeType(sfileData);
objInputStream.Close();
objInputStream.Dispose();
}
return objMimeType;
}
