.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"; } }
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!