Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how can I know the file type from a byte[]?

I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!

Thanks!!

like image 469
André Miranda Avatar asked Oct 31 '09 16:10

André Miranda


People also ask

What does '?' Mean in C?

Most likely the '?' is the ternary operator. Its grammar is: RESULT = (COND) ? ( STATEMEN IF TRUE) : (STATEMENT IF FALSE) It is a nice shorthand for the typical if-else statement: if (COND) { RESULT = (STATEMENT IF TRUE); } else { RESULT = (STATEMENT IF FALSE);

What is an operator in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What does |= mean in C++?

|= just assigns the bitwise OR of a variable with another to the one on the LHS.


1 Answers

As mentioned, MIME magic is the only way to do this. Many platforms provide up-to-date and robust MIME magic files and code to do this efficiently. The only way to do this in .NET without any 3rd party code is to use FindMimeFromData from urlmon.dll. Here's how:

public static int MimeSampleSize = 256;  public static string DefaultMimeType = "application/octet-stream";  [DllImport(@"urlmon.dll", CharSet = CharSet.Auto)] private extern static 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 GetMimeFromBytes(byte[] data) {     try {         uint mimeType;         FindMimeFromData(0, null, data, (uint)MimeSampleSize, null, 0, out mimeType, 0);          var mimePointer = new IntPtr(mimeType);         var mime = Marshal.PtrToStringUni(mimePointer);         Marshal.FreeCoTaskMem(mimePointer);          return mime ?? DefaultMimeType;     }     catch {         return DefaultMimeType;     } } 

This uses the Internet Explorer MIME detector. This is the same code used by IE to send a MIME type along with uploaded files. You can see the list of MIME types supported by urlmon.dll. One thing to watch out for is image/pjpeg and image/x-png which are non-standard. In my code I replace these with image/jpeg and image/png.

like image 152
mroach Avatar answered Sep 28 '22 03:09

mroach