Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

Determine the file type using C#

I have a web page that has the file upload component to upload the allowed document types only to my system (images only). I don't want to use the regular expression to determine the file type and using the extension.

Please let me know if there is any other means of determining file types in C#.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I've just converted my VB.NET class to C# to detect mime types. They will be identified by a mix of sniffing the first 256 Bytes of a file(urlmon.dll - f.e. used by internet explorer) and a set of known types.

You can also use it to check if the file is what it pretends to be(if the extension matches the type).

// check whether or not the uploaded file is an image:
var contentType = MimeTypes.GetContentType(FileUpload1.PostedFile.FileName);
if(contentType.StartsWith("image"))
{
    // do something with the image ...
}

Here's the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.IO;

public class MimeTypes
{
    private static List<string> knownTypes;

    private static Dictionary<string, string> mimeTypes;

    [DllImport("urlmon.dll", CharSet = CharSet.Auto)]
    private static extern UInt32 FindMimeFromData(
        UInt32 pBC, [MarshalAs(UnmanagedType.LPStr)]
        string pwzUrl, [MarshalAs(UnmanagedType.LPArray)]
        byte[] pBuffer, UInt32 cbSize, [MarshalAs(UnmanagedType.LPStr)]
        string pwzMimeProposed, UInt32 dwMimeFlags, ref UInt32 ppwzMimeOut, UInt32 dwReserverd
    );

    public static string GetContentType(string fileName)
    {
        if (knownTypes == null || mimeTypes == null)
            InitializeMimeTypeLists();
        string contentType = "";
        string extension = System.IO.Path.GetExtension(fileName).Replace(".", "").ToLower();
        mimeTypes.TryGetValue(extension, out contentType);
        if (string.IsNullOrEmpty(contentType) || knownTypes.Contains(contentType))
        {
            string headerType = ScanFileForMimeType(fileName);
            if (headerType != "application/octet-stream" || string.IsNullOrEmpty(contentType))
                contentType = headerType;
        }
        return contentType;
    }

    private static string ScanFileForMimeType(string fileName)
    {
        try
        {
            byte[] buffer = new byte[256];
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                int readLength = Convert.ToInt32(Math.Min(256, fs.Length));
                fs.Read(buffer, 0, readLength);
            }

            UInt32 mimeType = default(UInt32);
            FindMimeFromData(0, null, buffer, 256, null, 0, ref mimeType, 0);
            IntPtr mimeTypePtr = new IntPtr(mimeType);
            string mime = Marshal.PtrToStringUni(mimeTypePtr);
            Marshal.FreeCoTaskMem(mimeTypePtr);
            if (string.IsNullOrEmpty(mime))
                mime = "application/octet-stream";
            return mime;
        } catch (Exception ex)
        {
            return "application/octet-stream";
        }
    }

    private static void InitializeMimeTypeLists()
    {
        knownTypes = new string[] {
        "text/plain",
        "text/html",
        "text/xml",
        "text/richtext",
        "text/scriptlet",
        "audio/x-aiff",
        "audio/basic",
        "audio/mid",
        "audio/wav",
        "image/gif",
        "image/jpeg",
        "image/pjpeg",
        "image/png",
        "image/x-png",
        "image/tiff",
        "image/bmp",
        "image/x-xbitmap",
        "image/x-jg",
        "image/x-emf",
        "image/x-wmf",
        "video/avi",
        "video/mpeg",
        "application/octet-stream",
        "application/postscript",
        "application/base64",
        "application/macbinhex40",
        "application/pdf",
        "application/xml",
        "application/atom+xml",
        "application/rss+xml",
        "application/x-compressed",
        "application/x-zip-compressed",
        "application/x-gzip-compressed",
        "application/java",
        "application/x-msdownload"
    }.ToList();

        mimeTypes = new Dictionary<string, string>();
        mimeTypes.Add("3dm", "x-world/x-3dmf");
        mimeTypes.Add("3dmf", "x-world/x-3dmf");
        mimeTypes.Add("a", "application/octet-stream");
        mimeTypes.Add("aab", "application/x-authorware-bin");
        mimeTypes.Add("aam", "application/x-authorware-map");
        mimeTypes.Add("aas", "application/x-authorware-seg");
        mimeTypes.Add("abc", "text/vnd.abc");
        mimeTypes.Add("acgi", "text/html");
        mimeTypes.Add("afl", "video/animaflex");
        mimeTypes.Add("ai", "application/postscript");
        mimeTypes.Add("aif", "audio/aiff");
        mimeTypes.Add("aifc", "audio/aiff");
        mimeTypes.Add("aiff", "audio/aiff");
        mimeTypes.Add("aim", "application/x-aim");
        mimeTypes.Add("aip", "text/x-audiosoft-intra");
        mimeTypes.Add("ani", "application/x-navi-animation");
        mimeTypes.Add("aos", "application/x-nokia-9000-communicator-add-on-software");
        mimeTypes.Add("aps", "application/mime");
        mimeTypes.Add("arc", "application/octet-stream");
        mimeTypes.Add("arj", "application/arj");
        mimeTypes.Add("art", "image/x-jg");
        mimeTypes.Add("asf", "video/x-ms-asf");
        mimeTypes.Add("asm", "text/x-asm");
        mimeTypes.Add("asp", "text/asp");
        mimeTypes.Add("asx", "application/x-mplayer2");
        mimeTypes.Add("au", "audio/basic");
        mimeTypes.Add("avi", "video/avi");
        mimeTypes.Add("avs", "video/avs-video");
        mimeTypes.Add("bcpio", "application/x-bcpio");
        mimeTypes.Add("bin", "application/octet-stream");
        mimeTypes.Add("bm", "image/bmp");
        mimeTypes.Add("bmp", "image/bmp");
        mimeTypes.Add("boo", "application/book");
        mimeTypes.Add("book", "application/book");
        mimeTypes.Add("boz", "application/x-bzip2");
        mimeTypes.Add("bsh", "application/x-bsh");
        mimeTypes.Add("bz", "application/x-bzip");
        mimeTypes.Add("bz2", "application/x-bzip2");
        mimeTypes.Add("c", "text/plain");
        mimeTypes.Add("c++", "text/plain");
        mimeTypes.Add("cat", "application/vnd.ms-pki.seccat");
        mimeTypes.Add("cc", "text/plain");
        mimeTypes.Add("ccad", "application/clariscad");
        mimeTypes.Add("cco", "application/x-cocoa");
        mimeTypes.Add("cdf", "application/cdf");
        mimeTypes.Add("cer", "application/pkix-cert");
        mimeTypes.Add("cha", "application/x-chat");
        mimeTypes.Add("chat", "application/x-chat");
        mimeTypes.Add("class", "application/java");
        mimeTypes.Add("com", "application/octet-stream");
        mimeTypes.Add("conf", "text/plain");
        mimeTypes.Add("cpio", "application/x-cpio");
        mimeTypes.Add("cpp", "text/x-c");
        mimeTypes.Add("cpt", "application/x-cpt");
        mimeTypes.Add("crl", "application/pkcs-crl");
        mimeTypes.Add("css", "text/css");
        mimeTypes.Add("def", "text/plain");
        mimeTypes.Add("der", "application/x-x509-ca-cert");
        mimeTypes.Add("dif", "video/x-dv");
        mimeTypes.Add("dir", "application/x-director");
        mimeTypes.Add("dl", "video/dl");
        mimeTypes.Add("doc", "application/msword");
        mimeTypes.Add("dot", "application/msword");
        mimeTypes.Add("dp", "application/commonground");
        mimeTypes.Add("drw", "application/drafting");
        mimeTypes.Add("dump", "application/octet-stream");
        mimeTypes.Add("dv", "video/x-dv");
        mimeTypes.Add("dvi", "application/x-dvi");
        mimeTypes.Add("dwf", "drawing/x-dwf (old)");
        mimeTypes.Add("dwg", "application/acad");
        mimeTypes.Add("dxf", "application/dxf");
        mimeTypes.Add("eps", "application/postscript");
        mimeTypes.Add("es", "application/x-esrehber");
        mimeTypes.Add("etx", "text/x-setext");
        mimeTypes.Add("evy", "application/envoy");
        mimeTypes.Add("exe", "application/octet-stream");
        mimeTypes.Add("f", "text/plain");
        mimeTypes.Add("f90", "text/x-fortran");
        mimeTypes.Add("fdf", "application/vnd.fdf");
        mimeTypes.Add("fif", "image/fif");
        mimeTypes.Add("fli", "video/fli");
        mimeTypes.Add("flv", "video/x-flv");
        mimeTypes.Add("for", "text/x-fortran");
        mimeTypes.Add("fpx", "image/vnd.fpx");
        mimeTypes.Add("g", "text/plain");
        mimeTypes.Add("g3", "image/g3fax");
        mimeTypes.Add("gif", "image/gif");
        mimeTypes.Add("gl", "video/gl");
        mimeTypes.Add("gsd", "audio/x-gsm");
        mimeTypes.Add("gtar", "application/x-gtar");
        mimeTypes.Add("gz", "application/x-compressed");
        mimeTypes.Add("h", "text/plain");
        mimeTypes.Add("help", "application/x-helpfile");
        mimeTypes.Add("hgl", "application/vnd.hp-hpgl");
        mimeTypes.Add("hh", "text/plain");
        mimeTypes.Add("hlp", "application/x-winhelp");
        mimeTypes.Add("htc", "text/x-component");
        mimeTypes.Add("htm", "text/html");
        mimeTypes.Add("html", "text/html");
        mimeTypes.Add("htmls", "text/html");
        mimeTypes.Add("htt", "text/webviewhtml");
        mimeTypes.Add("htx", "text/html");
        mimeTypes.Add("ice", "x-conference/x-cooltalk");
        mimeTypes.Add("ico", "image/x-icon");
        mimeTypes.Add("idc", "text/plain");
        mimeTypes.Add("ief", "image/ief");
        mimeTypes.Add("iefs", "image/ief");
        mimeTypes.Add("iges", "application/iges");
        mimeTypes.Add("igs", "application/iges");
        mimeTypes.Add("ima", "application/x-ima");
        mimeTypes.Add("imap", "application/x-httpd-imap");
        mimeTypes.Add("inf", "application/inf");
        mimeTypes.Add("ins", "application/x-internett-signup");
        mimeTypes.Add("ip", "application/x-ip2");
        mimeTypes.Add("isu", "video/x-isvideo");
        mimeTypes.Add("it", "audio/it");
        mimeTypes.Add("iv", "application/x-inventor");
        mimeTypes.Add("ivr", "i-world/i-vrml");
        mimeTypes.Add("ivy", "application/x-livescreen");
        mimeTypes.Add("jam", "audio/x-jam");
        mimeTypes.Add("jav", "text/plain");
        mimeTypes.Add("java", "text/plain");
        mimeTypes.Add("jcm", "application/x-java-commerce");
        mimeTypes.Add("jfif", "image/jpeg");
        mimeTypes.Add("jfif-tbnl", "image/jpeg");
        mimeTypes.Add("jpe", "image/jpeg");
        mimeTypes.Add("jpeg", "image/jpeg");
        mimeTypes.Add("jpg", "image/jpeg");
        mimeTypes.Add("jps", "image/x-jps");
        mimeTypes.Add("js", "application/x-javascript");
        mimeTypes.Add("jut", "image/jutvision");
        mimeTypes.Add("kar", "audio/midi");
        mimeTypes.Add("ksh", "application/x-ksh");
        mimeTypes.Add("la", "audio/nspaudio");
        mimeTypes.Add("lam", "audio/x-liveaudio");
        mimeTypes.Add("latex", "application/x-latex");
        mimeTypes.Add("lha", "application/lha");
        mimeTypes.Add("lhx", "application/octet-stream");
        mimeTypes.Add("list", "text/plain");
        mimeTypes.Add("lma", "audio/nspaudio");
        mimeTypes.Add("log", "text/plain");
        mimeTypes.Add("lsp", "application/x-lisp");
        mimeTypes.Add("lst", "text/plain");
        mimeTypes.Add("lsx", "text/x-la-asf");
        mimeTypes.Add("ltx", "application/x-latex");
        mimeTypes.Add("lzh", "application/octet-stream");
        mimeTypes.Add("lzx", "application/lzx");
        mimeTypes.Add("m", "text/plain");
        mimeTypes.Add("m1v", "video/mpeg");
        mimeTypes.Add("m2a", "audio/mpeg");
        mimeTypes.Add("m2v", "video/mpeg");
        mimeTypes.Add("m3u", "audio/x-mpequrl");
        mimeTypes.Add("man", "application/x-troff-man");
        mimeTypes.Add("map", "application/x-navimap");
        mimeTypes.Add("mar", "text/plain");
        mimeTypes.Ad

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...