Home >Backend Development >C++ >How Can I Determine a File's MIME Type Using File Signatures in .NET?
The Mime type of accurately identifying files is essential for the correct processing and operation. When the file extension is lacking or incorrect, the file signature must be relying on the file type to accurately determine the file type. This article discusses how to achieve this function in the .NET.
solution using urlmon.dll
The solution provided using the URLmon.dll library to extract the MIME type based on the file signature. This method can be implemented through the following steps:
Introduce the necessary assembly set:
Define the FindMimefromdata function:
<code class="language-csharp">using System.Runtime.InteropServices;</code>
Create a function that searches the MIME type from the file:
<code class="language-csharp">[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 );</code>
<code class="language-csharp">public static string GetMimeFromFile(string filename) { // 为简洁起见,省略文件验证 byte[] buffer = new byte[256]; //... try { uint mimetype; FindMimeFromData(0, null, buffer, 256, 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"; } }</code>
Please note that some code is omitted in the above code fragments, such as the first 256 bytes of reading the file to the array. Complete implementation requires the necessary error processing and file reading logic. In addition, the use of method may depend on the operating system, and compatibility problems may be existed in different environments. More stable solutions may need to consider using other .NET libraries or implement file signature analysis by themselves.
The above is the detailed content of How Can I Determine a File's MIME Type Using File Signatures in .NET?. For more information, please follow other related articles on the PHP Chinese website!