How to discover the file extension through the Bytes array?

Asked

Viewed 1,351 times

4

I wonder if it is possible to get a get on the file extension through the Byte Array. Because I download a file from the server, and it can be both . JPEG and . EPS, however I am not able to know which file I received and I can’t define the MIME/Extension of the same (I am stuck in JPEG for example). Following 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");
  • The image_url does not end with . jpeg or . eps?

  • No, the image_url not direct access to image, it is a url with a Guid that authenticates on the server and returns the image.

  • Does this tool resolve: https://superuser.com/questions/274734/is-there-a-tool-that-can-determine-the-file-type-from-containing-data

  • @Fernando not because I need a solution inside the c#, outside it does not roll.

  • If you don’t find a better solution, you could run the TrID.exe inside C# as follows https://stackoverflow.com/questions/15234448/run-shell-commands-using-c-sharp-and-get-the-info-into-string

1 answer

3


Find the MIME type

Has the package Mime-Detective. It’s in the Nuget repository. You’d use it like this:

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

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

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

Determines the MIME type of the data provided

Follows a example of implementation, 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 the MIME string, which is exactly what you need. If for some reason you cannot, 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. So:

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

Being GetMimeType(byte[]) the method you will use to obtain this value.

  • In case it wasn’t what was asked

  • @vnbrs Solved my problem, but I still have a question related to MIME-Detective, which formats can he detect? because when I get one . EPS it says / MIME extension is txt

  • You should return any of these: application/Postscript, application/eps, application/x-eps, image/eps, image/x-eps. I don’t know how it behaves about this type of file, but you can treat or try the other method with that dll I mentioned in the answer.

  • 1

    @vnbrs is that the library does not yet support EPS... but anyway solved my problem, I will mark as correct, I used this library even ! I’ll even collaborate with the project by adding the EPS ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.