zoukankan      html  css  js  c++  java
  • 利用Win32API 读取文件头获取MimeType

    第一个种方式利用Win32API 读取文件头获取Mime-Type

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

    public string getMimeFromFile(string filename)
    {
    if (!File.Exists(filename))
    throw new FileNotFoundException(filename + " not found");

    byte[] buffer = new byte[256];
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
    if (fs.Length >= 256)
    fs.Read(buffer,
    0, 256);
    else
    fs.Read(buffer,
    0, (int)fs.Length);
    }
    try
    {
    System.UInt32 mimetype;
    FindMimeFromData(
    0, null, buffer, 256, null, 0, out mimetype, 0);
    System.IntPtr mimeTypePtr
    = new IntPtr(mimetype);
    string mime = Marshal.PtrToStringUni(mimeTypePtr);
    Marshal.FreeCoTaskMem(mimeTypePtr);
    return mime;
    }
    catch (Exception e)
    {
    return "unknown/unknown";
    }
    }

    第二种方式 利用系统注册表查找Mime-Type

    using System.IO;
    using Microsoft.Win32;

    string GetMimeType(FileInfo fileInfo)
    {
    string mimeType = "application/unknown";

    RegistryKey regKey
    = Registry.ClassesRoot.OpenSubKey(
    fileInfo.Extension.ToLower()
    );

    if(regKey != null)
    {
    object contentType = regKey.GetValue("Content Type");

    if(contentType != null)
    mimeType
    = contentType.ToString();
    }

    return mimeType;
    }



    返回导读目录,阅读更多随笔



    分割线,以下为博客签名:

    软件臭虫情未了
    • 编码一分钟
    • 测试十年功


    随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

  • 相关阅读:
    搭建jenkins jmeter持续集成
    Jenkins windows环境搭建
    Appium环境搭建(二)
    Qt webkitwidgets模块和webenginewidgets模块
    Qt程序无法输入中文的问题
    在Qt中使用SQLite数据库
    Ubuntu下搜狗拼音输入法打不出汉字的解决方法
    drupal7创始人root忘记密码的解决办法
    javascript块级作用域
    javascript闭包
  • 原文地址:https://www.cnblogs.com/08shiyan/p/2063102.html
Copyright © 2011-2022 走看看