public virtual PortableDeviceFolder GetContents(int?depth, bool folderOnly) { var root = new PortableDeviceFolder("DEVICE", FriendlyName); var queue = new Queue <PortableDeviceObject>(); device.Content(out IPortableDeviceContent content); content.Properties(out IPortableDeviceProperties properties); try { EnumerateContents(ref content, ref properties, root, queue, depth, folderOnly); while (queue.Count > 0) { var currentItem = queue.Dequeue(); if (currentItem is PortableDeviceFolder nextFolder) { EnumerateContents(ref content, ref properties, nextFolder, queue, --depth, folderOnly); } } return(root); } finally { Marshal.ReleaseComObject(content); Marshal.ReleaseComObject(properties); } }
private void EnumerateContents(ref IPortableDeviceContent content, ref IPortableDeviceProperties properties, PortableDeviceFolder parent, Queue <PortableDeviceObject> queue, int?depth, bool folderOnly = false) { content.EnumObjects(0, parent.Id, null, out IEnumPortableDeviceObjectIDs objectIDs); try { uint fetched = 0; do { objectIDs.Next(1, out string nextObjectIDs, ref fetched); if (fetched > 0) { var item = WrapObject(properties, nextObjectIDs); if (!folderOnly || item.IsFolder) { parent.Files.Add(item); } if (depth == null || depth > 1) { queue.Enqueue(item); } } } while (fetched > 0); } finally { Marshal.ReleaseComObject(objectIDs); } }