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.
The
image_url
does not end with . jpeg or . eps?– vinibrsl
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.– Leonardo Bonetti
Does this tool resolve: https://superuser.com/questions/274734/is-there-a-tool-that-can-determine-the-file-type-from-containing-data
– Fernando
@Fernando not because I need a solution inside the c#, outside it does not roll.
– Leonardo Bonetti
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– Fernando