Monday, December 24, 2018

Retrieve MimeType by its extension

In file IO, we need to set content/type while downloading it and this should be dynamically set by file's extension. Here is code we can use to do the same

Create static class to store all available mime-type, here am showing few only, we can add more.


public static class MimeTypesHelper
        {
            public const string
            Doc = "application/msword",
            Docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            Xls = "application/vnd.ms-excel",
            Xlt = "application/vnd.ms-excel",
            Xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            Ppt = "application/vnd.ms-powerpoint",
            Pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            Pdf = "application/pdf",
            Zip = "application/zip";


            //get matched mime type by extension, so property name should be equals to file extension
            public static string GetMimeTypeByExtension(string extension)
            {
                //remove period in extension
                extension = extension?.Replace(".", "");
                //match mimetype by property
                string matchedMimeType = typeof(MimeTypes).GetField(extension, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)?.GetValue(null)?.ToString();

                //if there is no match default to octet stream
                if (string.IsNullOrEmpty(matchedMimeType))
                {
                    matchedMimeType = "application/octet-stream";
                }

                return matchedMimeType;
            }
        }


Call this method to retrieve your file mimetype

 Response.ContentType = MimeTypesHelper.GetMimeTypeByExtension(".pdf");   //this will return "application/pdf"



No comments:

Post a Comment