<.> Use the file signature in the .NET to determine the file type of the file
In many cases, the type of MIME in accurately identifying files is very important, especially when the file extension is incorrect or does not exist. .NET provided a general solution for this.
In .NET, developers can use the
function in the URLmon.dll library. This function uses a signature solution to determine the MIME type of the file.
FindMimeFromData
To achieve this technology, please follow the steps below:
<code class="language-csharp"> using System.Runtime.InteropServices;</code>
<code class="language-csharp"> byte[] buffer = new byte[256];</code>
<code class="language-csharp"> 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); }</code>
FindMimeFromData
<code class="language-csharp"> uint mimetype; FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0); IntPtr mimeTypePtr = new IntPtr((int)mimetype); // 修正:将mimetype强制转换为int string mime = Marshal.PtrToStringUni(mimeTypePtr); Marshal.FreeCoTaskMem(mimeTypePtr);</code>
By implementing this solution, developers can reliably determine the MIME type of the file based on the signature of the file, regardless of the file extension. This technology is very valuable in various applications, including file upload processing and content delivery.
In the original code
There are potential problems, because is the type, and the constructor accepts the new IntPtr(mimetype)
type. The modified code converts to mimetype
to ensure compatibility. This is especially important when dealing with .NET implementation of different platforms. UInt32
The above is the detailed content of How Can I Determine a File's MIME Type Using its Signature in .NET?. For more information, please follow other related articles on the PHP Chinese website!