Skip to content

hey-red/Mime

Repository files navigation

Mime

.NET wrapper for libmagic

NuGet license

Install

viaNuGet:

PM> Install-Package Mime

Requirements

Supported runtimes:

  • linux-musl-x64
  • linux-x64
  • osx-arm64(tested on macOS 13 Ventura)
  • osx-x64
  • win-x64

Basic usage

usingHeyRed.Mime;

// (Optionally) You can set path to magic database file manually.
MimeGuesser.MagicFilePath="/path/to/magic.mgc";

// Guess mime type of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessMimeType("path/to/file");//=> image/jpeg

// Get extension of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessExtension("path/to/file");//=> jpeg

// Get mime type and extension of file(overloaded method takes byte array or stream as arg.)
MimeGuesser.GuessFileType("path/to/file");//=> FileType

Advanced

Want more than just the mime type? Use the Magic class:

stringcalc=@ "C:\Windows\System32\calc.exe";
usingvarmagic=newMagic(MagicOpenFlags.MAGIC_NONE);
magic.Read(calc);//=> PE32+ executable (GUI) x86-64, for MS Windows

// Check encoding:
stringtextFile=@ "F:\Temp\file.txt";
usingvarmagic=newMagic(MagicOpenFlags.MAGIC_MIME_ENCODING);
magic.Read(textFile);//=> Output: utf-8

Also, we can combine flags with "|" operator. See allflagsfor more info.

Remarks

  • The Magic class is not thread safe, but if you use different instances on different threads it seems to work fine.
  • The MimeGuesser is thread safe, since it generates a new instance of Magic class on each use.

Possible problems

Exception Solution
DllNotFoundException Make sure that yourbinfolder contains runtimes directory. If you publishing platform dependent app, thenbinshould be containslibmagic-1(.dll,.so or.dylib) andmagic.mgcfiles.
BadImageFormatException Make sure when you target theAnyCPUplatform thePrefer 32-bitoption is unchecked. Or try to targetx64/arm64instead.
MagicException: Could not find any valid magic files! Make sure your magic.mgc file contains in one of /runtimes/ subdirs or along with libmagic-1.[dll|lib|dylib]. Or set path to custom database as described inbasic usage

License

MIT