[Xamarin iOS] How to get the mime type of a file ?

December 5th, 2016 | Posted by Tom in .NET | Xamarin | Read: 1,659

For the project I’m currently working on (a Xamarin.iOs application), I needed to find a way to retrieve the mime type of a file, based on its extension.

After looking on Internet, I’ve found that I needed to use the classes UTTypeCopyPreferredTagWithClass and UTTypeCreatePreferredIdentifierForTag which are in MobieCoreServices. Unfortunately, this methods are not directly exposed by Xamarin so you can’t call these methods directly.

But, fortunately, thanks to the P/Invoke process, it’s still possible to use them!

Indeed, first, you need to declare the specific mapping to the native functions:

public static class NativeTools
{
    [DllImport(ObjCRuntime.Constants.MobileCoreServicesLibrary, EntryPoint = "UTTypeCopyPreferredTagWithClass")]
    public extern static IntPtr UTTypeCopyPreferredTagWithClass(IntPtr uti, IntPtr tagClass);

    [DllImport(ObjCRuntime.Constants.MobileCoreServicesLibrary, EntryPoint = "UTTypeCreatePreferredIdentifierForTag")]
    public extern static IntPtr UTTypeCreatePreferredIdentifierForTag(IntPtr tagClass, IntPtr tag, IntPtr uti);
}

Then, you just have to use the exposed functions in your own code:

public string GetMimeType(string fileName)
{
    var extensionWithDot = Path.GetExtension(fileName);
    if (!string.IsNullOrWhiteSpace(extensionWithDot))
    {
        var extension = extensionWithDot.Substring(1);
        if (!string.IsNullOrWhiteSpace(extension))
        {
            var extensionClassRef = new NSString(UTType.TagClassFilenameExtension);
            var mimeTypeClassRef = new NSString(UTType.TagClassMIMEType);

            var uti = NativeTools.UTTypeCreatePreferredIdentifierForTag(extensionClassRef.Handle, new NSString(extension).Handle, IntPtr.Zero);
            var mimeType = NativeTools.UTTypeCopyPreferredTagWithClass(uti, mimeTypeClassRef.Handle);
            using (var mimeTypeCString = new CoreFoundation.CFString(mimeType))
            {
                return mimeTypeCString;
            }
        }
    }

    return string.Empty;
}

Once executed, the code will get the correct mime type:

image

I hope that will be helpful to some of you!

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Add Comment Register



Leave a Reply