Home > Backend Development > C++ > How to Determine a File's MIME Type Using its Signature in .NET?

How to Determine a File's MIME Type Using its Signature in .NET?

DDD
Release: 2025-01-31 15:01:09
Original
741 people have browsed it

How to Determine a File's MIME Type Using its Signature in .NET?

determine the MIME type

.NET framework provided a method of file -based signature instead of expanding name recognition file MIME type. This is particularly useful when processing incorrect or missing files.

To determine the MIME type, you can use the

exported

function. This function receives the byte buffer of the file signature and returns its MIME type. urlmon.dll FindMimeFromData The following is an example of how to use this function to use this function:

This method provides a reliable method that can only obtain its MIME type based on the signature of the file, regardless of the extension. The code improvement is that it is more accurate to handle the number of bytes read to avoid the problem of potential array crossing the border.
using System.Runtime.InteropServices;
...

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

public static 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))
    {
        int bytesRead = fs.Read(buffer, 0, 256); // Read at most 256 bytes
        if (bytesRead < 256)
        {
            Array.Resize(ref buffer, bytesRead); // Resize buffer if less than 256 bytes were read
        }
    }
    try
    {
        uint mimetype;
        FindMimeFromData(0, null, buffer, (uint)buffer.Length, null, 0, out mimetype, 0);
        IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        return "unknown/unknown";
    }
}
Copy after login

The above is the detailed content of How to Determine a File's MIME Type Using its Signature in .NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template