xdg_mime allows to look up the MIME type associated to a file name
or to the contents of a file, using the Freedesktop.org Shared MIME
Alongside the MIME type, the shared MIME database contains other ancillary information, like the icon associated to the MIME type; the aliases for a given MIME type; and the various sub-classes of a MIME type.
SharedMimeInfo type will automatically
load all the instances of shared MIME databases available in the following
directories, in this specified order:
XDG_DATA_HOMEis unset, this corresponds to
XDG_DATA_DIRSis unset, this corresponds to
For more information on the
variables, see the XDG base directory specification.
The MIME data in each directory will be coalesced into a single database.
If you want to know the MIME type of a file, you typically have two options at your disposal:
- guess from the file name, using the
- use an appropriately sized chunk of the file contents and
perform “content sniffing”, using the
The former step does not come with performance penalties, or even requires the file to exist in the first place, but it may return a list of potential matches; the latter can be an arbitrarily expensive operation to perform, but its result is going to be certain. It is recommended to always guess the MIME type from the file name first, and only use content sniffing lazily and, possibly, asynchronously.
If you have access to a file name or its contents, it’s possible to use
guess_mime_type method to create a
GuessBuilder instance, and
populate it with the file name, its contents, or the full path to the file;
then, call the
guess method to guess the MIME type depending on the
A builder type to specify the parameters for guessing a MIME type.
The shared MIME info database.