hey-red / Mime

.NET wrapper for libmagic
MIT License
82 stars 21 forks source link

Problem with executable files #57

Open FarazZvd opened 1 week ago

FarazZvd commented 1 week ago

Hi there. I need files' extensions to be detected based on their content and this library has proved to be alright for doing this except one inconvenience. When dealing with executable files in windows, I need the exact extension which should "exe" -as the Path.GetExtension() provides from file name- but instead, I get "bin" which I don't find quite useful, at least for my use case. Am I missing something here or should I manually handlethis scenario in my project?

hey-red commented 1 week ago

Yes. When you need to work with extensions you should do it by yourself. One mime type can have multiple extensions, and in addition, libmagic may not contain an extension for a specific type.

For example:

public class FileTypeGuesser
{
    private static readonly Dictionary<string, string> _extensionsOverrides = new()
    {
        ["application/vnd.microsoft.portable-executable"] = "exe",
    };

    public FileType GuessType(Stream input)
    {
        var fileType = MimeGuesser.GuessFileType(input);

        string mimeType = fileType.MimeType;
        string extension = fileType.Extension;

        if (_extensionsOverrides.TryGetValue(mimeType, out var overridedExtension))
        {
            return new FileType(mimeType, overridedExtension);
        }

        return new FileType(mimeType, extension);
    }
}
FarazZvd commented 1 week ago

Thanks a lot. Do you think it would be helpful if I pulled your project and add these kind of extension-based features? I'm currently checking to see how useful it would be compared to just handling this case out of Mime library. I would appreciate your opinion.