【问题标题】:how to identify the extension/type of the file using C#?如何使用 C# 识别文件的扩展名/类型?
【发布时间】:2011-02-19 02:05:29
【问题描述】:

我有一个工作流程,允许用户上传任何文件,然后读取该文件。

现在我的问题是,如果用户有图像文件 xyz.jpg 并且他仅将其重命名为 xyz(已删除扩展名),我们仍然可以使用/读取文件数据/元数据来获取文件的类型/扩展名。

谢谢大家

【问题讨论】:

  • 不要让他们上传没有扩展名的文件! :)
  • [使用 .NET,如何根据文件签名而不是扩展名找到文件的 MIME 类型的可能重复项。 ](stackoverflow.com/questions/58510/…)
  • 我同意 - 没有扩展名的文件对用户的价值值得怀疑,是什么让他们认为它们对您更有价值?这不是预期的行为,不会对您产生额外的复杂性。

标签: c#


【解决方案1】:

是的,可能对于许多文件类型来说这是可能的,但需要根据具体情况解析文件的二进制内容。

【讨论】:

    【解决方案2】:

    您可以在 urlmon.dll 中使用非托管函数FindMimeFromData。

    using System.Runtime.InteropServices;
    
    [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
    );
    

    请参阅here 以获取示例用法。

    【讨论】:

    • +1 - 很酷,不知道。你认为 HttpPostedFile 的 ContentType 是通过咨询这个来设置的吗?另外 - 找到另一个 q 代码示例:stackoverflow.com/questions/58510/…
    • @Andras 发布文件的内容类型由发布者任意设置(代码、浏览器、flash 等),除非您有严格控制的环境,否则不得依赖。
    • 我注意到了这一点并立即取消删除。 ;-) 并同意其他观点。
    • 这很聪明。抱歉我的回答不好!你每天都会学到新东西!
    • @code 诗人 - 在我的回答中(已删除,因为这个和你的,+1 也顺便说一句,是优越的)我向 OP 提到实际上 ContentType 是不可靠的。
    【解决方案3】:

    详情请见PInvoke.net

       [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
        static extern int FindMimeFromData(IntPtr pBC,
              [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
             [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] 
            byte[] pBuffer,
              int cbSize,
                 [MarshalAs(UnmanagedType.LPWStr)]  string pwzMimeProposed,
              int dwMimeFlags,
              out IntPtr ppwzMimeOut,
              int dwReserved);
    

    示例用法:

      public string MimeTypeFrom(byte[] dataBytes, string mimeProposed) {
       if (dataBytes == null)
         throw new ArgumentNullException("dataBytes");
       string mimeRet = String.Empty;
       IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr = IntPtr.Zero;
       if (mimeProposed != null && mimeProposed.Length > 0) {
         //suggestPtr = Marshal.StringToCoTaskMemUni(mimeProposed); // for your experiments ;-)
         mimeRet = mimeProposed;
       }
       int ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, mimeProposed, 0, out outPtr, 0);
       if (ret == 0 && outPtr != IntPtr.Zero) {
        //todo: this leaks memory outPtr must be freed
         return Marshal.PtrToStringUni(outPtr);
       }
       return mimeRet;
    }
    
    // call it this way:
    Trace.Write("MimeType is " + MimeTypeFrom(Encoding.ASCII.GetBytes("%PDF-"), "text/plain"));
    

    另一个例子:

    /// <summary>
    /// Ensures that file exists and retrieves the content type 
    /// </summary>
    /// <param name="file"></param>
    /// <returns>Returns for instance "images/jpeg" </returns>
    public static string getMimeFromFile(string file)
    {
        IntPtr mimeout;
        if (!System.IO.File.Exists(file))
        throw new FileNotFoundException(file + " not found");
    
        int MaxContent = (int)new FileInfo(file).Length;
        if (MaxContent > 4096) MaxContent = 4096;
        FileStream fs = File.OpenRead(file);
    
    
        byte[] buf = new byte[MaxContent];        
        fs.Read(buf, 0, MaxContent);
        fs.Close();
        int result = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, null, 0, out mimeout, 0);
    
        if (result != 0)
        throw Marshal.GetExceptionForHR(result);
        string mime = Marshal.PtrToStringUni(mimeout);
        Marshal.FreeCoTaskMem(mimeout);
        return mime;
    }
    

    【讨论】:

      【解决方案4】:

      您是否需要检测特定的文件格式?如果您可以将范围缩小到可以通过文件内容识别的几种格式,则任务会变得容易得多。

      如果您需要检测范围广泛的文件类型,可以使用第三方工具包,但我会警告您,它们往往非常昂贵。我熟悉的两个是Stellent's (now Oracle's) Outside In和Autonomy Keyview。两者都提供程序员工具包。

      【讨论】:

        【解决方案5】:

        如果只需要查看上传的文件是否为Image,则进行相应的解析

        try
        {
        Image image = Bitmap.FromStream(fileData);
        }
        catch(Exception e)
        {
            // this isn't an image.
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-04-22
          • 2015-04-02
          • 1970-01-01
          • 2019-02-06
          • 2012-05-22
          • 2015-05-24
          • 1970-01-01
          相关资源
          最近更新 更多