Search code examples
macoscocoaxamarinxamarin.mac

MDItem Class In Xamarin


I'm trying to read comment field from file. enter image description here

Found this thread about how to do it, but can't find MDItem corresponding class in Xamarin.

Any ideas where to find it or what to use instead?


Solution

  • Some of the CoreServices are not wrapped within the current Xamarin.Mac (Version: 2.10.0.57).

    Most of them pass CFxxxx-based references around, so they are easy to wrap and implement via some Interop calls.

    Finder-based File comment

    enter image description here

    Code Example:

    var fileURL = NSUrl.FromString("/Users/sushi/Desktop/DFeedback_FeedBack.png");
    var mMDItemRef = MDItemCreateWithURL(IntPtr.Zero, fileURL.Handle);
    
    var mCFTypeRef = MDItemCopyAttribute(mMDItemRef, new CFString("kMDItemFinderComment").Handle);
    var finderComment = NSString.FromHandle(mCFTypeRef);
    Console.WriteLine(finderComment);
    

    Note: The interop calls should be tested for null in production code, see return signature comments in header file.

    Application Output:

    StackOverflow
    

    Interop setup:

    // @function MDItemCreateWithURL
    // Returns an metadata item for the given path.
    // @param allocator The CFAllocator which should be used to allocate
    // memory for the query and its sub-storage.This
    // parameter may be NULL in which case the current default
    // CFAllocator is used.
    // @param url A url to the file for which to create the MDItem.
    // [[Currently, the file must exist.MDItemRefs may or
    // may not be uniqued.Use CFEqual() to compare them.]]
    // @result An MDItemRef, or NULL on failure.
    
    //MD_EXPORT MDItemRef MDItemCreateWithURL(CFAllocatorRef allocator, CFURLRef url) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER;
    [DllImport(Constants.CoreServicesLibrary)]
    extern static /* MDItemRef */ IntPtr MDItemCreateWithURL(/* CFAllocatorRef __nullable */ IntPtr allocator, /* CFURLRef */ IntPtr inURL);
    
    //@function MDItemCopyAttribute
    //Returns the value of the given attribute for the item.
    //@param item The item to be interrogated.
    //@param name The name of the desired attribute.
    //@result A CFTypeRef, or NULL on failure, or if the attribute
    //does not exist, of if the attribute is not readable.
    
    //MD_EXPORT CFTypeRef MDItemCopyAttribute(MDItemRef item, CFStringRef name) MD_AVAIL;
    [DllImport(Constants.CoreServicesLibrary)]
    extern static /* CFTypeRef */ IntPtr MDItemCopyAttribute(/* MDItemRef */ IntPtr item, /* CFStringRef */ IntPtr name);
    

    Xcode Obj-C Header Reference:

    MDItem.h
    

    Local Xcode Ref:: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/Metadata.framework/Versions/A/Headers