0

I am using the following code to copy a file wrapped by a FileInfo object to an MTP device using the Windows Portable Device API:

public static void CopyFileToDevice(PortableDeviceFolder parent, string name, FileInfo file)
    {
        IPortableDeviceValues values = GetRequiredPropertiesForContentType(parent.Id, name, file.Length);

        PortableDeviceApiLib.IStream tempStream;
        uint blockSize = 0;
        parent.Device.Content.CreateObjectWithPropertiesAndData(
            values,
            out tempStream,
            ref blockSize,
            null);

        System.Runtime.InteropServices.ComTypes.IStream targetStream =
            (System.Runtime.InteropServices.ComTypes.IStream)tempStream;
        try
        {
            using (var sourceStream = file.OpenRead())
            {
                var buffer = new byte[blockSize];
                int bytesRead;
                do
                {
                    bytesRead = sourceStream.Read(buffer, 0, (int)blockSize);
                    targetStream.Write(buffer, bytesRead, IntPtr.Zero);
                } while (bytesRead > 0);
            }

            targetStream.Commit(0);
        }
        finally
        {
            Marshal.ReleaseComObject(tempStream);
        }
        parent.Refresh();
    }

Now, this works quite fine, however when writing a small file, in this case a text-only .m3u file of a couple of kiB, the line

targetStream.Commit(0);

takes extremely long to execute. When writing a file of several MiB, nothing is wrong. I would like to know why this is happening and how I might fix this. Thanks!

NinjaTuna
  • 41
  • 5
  • Does the Windows File Explorer become unresponsive at the same time? Does the Windows Device Manager list the device under Other Devices and/or Portable Devices? – Jason Harrison Oct 23 '15 at 20:14
  • @JasonHarrison Windows Explorer indeed becomes unresponsive during the hang. Windows Device Manager has my phone listed under Portable Devices. – NinjaTuna Oct 25 '15 at 20:48
  • The only solution is to put the file write activity on a separate thread. Unfortunately, I don't know why the delay happens. I have seen similar delays when working with devices with many (thousands) of files and it appears to occur because Windows 8 is scanning the entire file/object structure of the device. In my specific case, the device is also creating files as my app is writing/removing files so file creation/change events may be triggering the scan. – Jason Harrison Nov 01 '15 at 13:52
  • Which Windows version are you running this on? What is the time duration for "extremely long" when writing the the small file? Should you be checking for any return values from targetStream.write() ? Is the size of the file written smaller than blockSize? – Jason Harrison Nov 01 '15 at 14:11

0 Answers0