4

I want to copy at least one file to a windows phone via MTP. I am able to connect to the phone and copy files from the phone to the computer following this tutorial: WPD: Transferring Content However I am unable to copy files the other way round (from computer to phone). This is my code:

IPortableDeviceContent content;
this._device.Content(out content);
IPortableDeviceValues values = GetRequiredPropertiesForContentType(fileName, parentObjectId);

PortableDeviceApiLib.IStream tempStream;
uint optimalTransferSizeBytes = 0;
content.CreateObjectWithPropertiesAndData(
     values,
     out tempStream,
     ref optimalTransferSizeBytes,
     null);

System.Runtime.InteropServices.ComTypes.IStream targetStream = (System.Runtime.InteropServices.ComTypes.IStream)tempStream;

try
{
    using (var sourceStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    {
        var buffer = new byte[optimalTransferSizeBytes];
        int bytesRead;
        do
        {
            bytesRead = sourceStream.Read(buffer, 0, (int)optimalTransferSizeBytes);
            IntPtr pcbWritten = IntPtr.Zero;
            targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);
        } while (bytesRead > 0);

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

I tested this code on several devices. It works on a normal mp3 player and assuming the tutorial is correct, it also works on an Android phone. But running this code with two different windows phone, I get following exception:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in      PortableDevices.exe

Additional information: The data area passed to a system call is too small. (Exception from HRESULT: 0x8007007A)

at this row: targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);

The buffer size is 262144 Byte, while the filesize is only 75 KByte. I hope someone has an idea how to fix this issue.

Greetings j0h4nn3s

j0h4nn3s
  • 2,016
  • 2
  • 20
  • 35

1 Answers1

2

I had the same issue, turns out the author made a simple mistake. You're writing the size of the buffer instead of the numbers you bytes you read.

Replace

targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);

by

targetStream.Write(buffer, bytesRead, pcbWritten);
RedXVII
  • 867
  • 6
  • 12
  • already fixed this issue earlier. Thanks for your answer, I hope this will help others in the future. – j0h4nn3s Jan 22 '15 at 10:07