Get Content Type by Extension : File Name « File Stream « C# / C Sharp






Get Content Type by Extension

      

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Security;

class Utilities
{
    public static string GetContentType(string extension)
    {
        string mimeType = "application/unknown";

        try
        {
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(extension, false);

            if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();
            else
            {
                switch (extension)
                {
                    case ".xap":
                        mimeType = "application/x-silverlight-app";
                        break;
                }
            }

            return mimeType;
        }
        catch (SecurityException)
        {
        }

        switch (extension)
        {
            case ".docx":
            case ".doc":
                mimeType = "application/msword";
                break;

            case ".jpg":
            case ".jpeg":
                mimeType = "image/jpeg";
                break;

            case ".png":
                mimeType = "image/png";
                break;

        }

        return mimeType;
    }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Query file name with Linq
2.Clean File Name
3.Retrieves the date from the beginning of the WinSat filename and creates a datetime object from it
4.Get File Name
5.Convert To Legal File Name
6.Get File Name From Path
7.Extracts a path part of a full path filename, searching for the last directory separator or column.
8.Creates a relative path from absolute pathfilename and a reference path.
9.Get file extension
10.Restrict a list of files to valid extensions only
11.Get Full Path Without Extension
12.Full Name Without Extension
13.Name Without Extension
14.ImageFormat to Extension
15.Gets the extension without the dot
16.Get Image Type Extension