How to find out the file extension through the Bytes array?

4

I wonder if it is possible to give a get in the file extension through the Bytes Array. Well, I downloaded a file from the server, and it can be either .JPEG or .EPS, but I'm not able to know what file I got and I can not set the MIME / Extension (I'm stuck in JPEG for example). Here's an example:

byte[] myDataBuffer = myWebClient.DownloadData(image_url);
//Gostaria de reconhecer o formato para tratar a linha posterior
return File(myDataBuffer, "image/jpeg", "Imagem-"+imageID+".jpeg");
    
asked by anonymous 26.12.2017 / 17:30

1 answer

3

Find the MIME type

You have the Mime-Detective package. It has in the NuGet repository. You would use it like this:

byte[] myDataBuffer = myWebClient.DownloadData(image_url);
FileType fileType = myDataBuffer.GetFileType();

It reads the header data from the file itself, not the extension, as most do.

Another solution, native to Windows, is to use the FindMimeFromData of urlmon.dll .

  

Determines the MIME type of the data provided

Here's an example of SOen:

using System.Runtime.InteropServices;
// ...
[DllImport(@"urlmon.dll", CharSet = CharSet.Auto)]
private extern static System.UInt32 FindMimeFromData(
    System.UInt32 pBC,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzUrl,
    [MarshalAs(UnmanagedType.LPArray)] byte[] pBuffer,
    System.UInt32 cbSize,
    [MarshalAs(UnmanagedType.LPStr)] System.String pwzMimeProposed,
    System.UInt32 dwMimeFlags,
    out System.UInt32 ppwzMimeOut,
    System.UInt32 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))
    {
        if (fs.Length >= 256)
            fs.Read(buffer, 0, 256);
        else
            fs.Read(buffer, 0, (int)fs.Length);
    }
    try
    {
        System.UInt32 mimetype;
        FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
        System.IntPtr mimeTypePtr = new IntPtr(mimetype);
        string mime = Marshal.PtrToStringUni(mimeTypePtr);
        Marshal.FreeCoTaskMem(mimeTypePtr);
        return mime;
    }
    catch (Exception e)
    {
        return "unknown/unknown";
    }
}

The function will return MIME in string, which is exactly what you need. If for some reason you can not, you will receive unknown/unknown .

and then the extension ...

The extension is usually the second part of the MIME type, at least in the cases you need: jpeg and eps. Here's how:

var mimeType = GetMimeType(file); // "image/jpeg"
var fileExtension = mimeType.Split('/').Last(); // "jpeg"

Being GetMimeType(byte[]) the method you will do to get this value.

    
26.12.2017 / 18:02