String extension method which returns the content type of a file determined by its extension. - CSharp System.IO

CSharp examples for System.IO:File Name

Description

String extension method which returns the content type of a file determined by its extension.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;//from w w w  . j a v  a2  s .co m

public class Main{
        /// <summary>
        /// String extension method which returns the content type of a file determined by its extension.
        /// </summary>
        /// <param name="fileExtension">The extension of a filename represented as a string on which the method is invoked.</param>
        /// <returns>Returns the content type if known, "application/octet-stream" - otherwise.</returns>
        public static string ToContentType(this string fileExtension)
        {
            var fileExtensionToContentType = new Dictionary<string, string>
                                                 {
                                                     { "jpg", "image/jpeg" },
                                                     { "jpeg", "image/jpeg" },
                                                     { "png", "image/x-png" },
                                                     {
                                                         "docx",
                                                         "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                                                     },
                                                     { "doc", "application/msword" },
                                                     { "pdf", "application/pdf" },
                                                     { "txt", "text/plain" },
                                                     { "rtf", "application/rtf" }
                                                 };
            if (fileExtensionToContentType.ContainsKey(fileExtension.Trim()))
            {
                return fileExtensionToContentType[fileExtension.Trim()];
            }

            return "application/octet-stream";
        }
}

Related Tutorials