neilharvey / FileSignatures

A small library for detecting the type of a file based on header signature (also known as magic number).

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Problem with validation of .jpg

ita-alibb opened this issue · comments

Hi, is it normal that i can't validate with default Inspector this dummy jpg file here? I have version 4.4.0
SBZ

Thank you

Hey, it seems to be working for me - here's a sample test which recognises the file:
https://github.com/neilharvey/FileSignatures/blob/sample-jpeg-not-matched/test/FileSignatures.Tests/JpegTests.cs

Are all the default formats definitely being registered?

Thank you for your response.
Yes, i can see all formats.
The problem maybe is that due to some business logic i have a byte[] representation of the file, i can't load it as new FileInfo.

i can't load it as new FileInfo.

You don't need FileInfo. FileSignatures accepts a Stream. As an example, a utility class I built for my needs:

public static class FileHelper
{
    public static string DetectMediaType(byte[] fileData)
    {
        using (var ms = new MemoryStream(fileData))
        {
            return DetectMediaType(ms);
        }
    }

    public static string DetectMediaType(Stream stream)
    {
        string mediaType = System.Net.Mime.MediaTypeNames.Application.Octet; 

        if (stream == null)
        {
            mediaType = null;
        }
        else
        {
            if (stream.CanRead)
            {
                var inspector = GetInspector();
                if (inspector != null)
                {
                    var format = inspector.DetermineFileFormat(stream);
                    if (format != null)
                    {
                        mediaType = format.MediaType;
                    }
                }
            }
        }

        return mediaType;
    }

    private static IFileFormatInspector inspector;
    private static IFileFormatInspector GetInspector() 
    {
        if (inspector == null)
        {
            inspector = new FileFormatInspector();
        }

        return inspector; 
    }
}

You can call it either directly with the byte array or pass in a stream:

byte[] your_byte_array = /* wherever your binary data comes from */
string mediaType = FileHelper.DetectMediaType(your_byte_array);

or

Stream your_stream = /* however you acquire or create a Stream instance */
string mediaType = FileHelper.DetectMediaType(your_stream);

Thank you, that's exactly how i am using it, but when i send the attachment the first two bytes are 254 69 which does not belong to any extension.
Anyway the problem is definitely on my side, thank you for trying to help me!

@neilharvey Sounds like this can be closed?

@tiesont Agreed, I'll close it off.