我想通过MTP将至少一个文件复制到
Windows手机.
根据本教程,我可以连接到手机并将文件从手机复制到计算机:
但是我无法以相反的方式复制文件(从计算机到手机).
这是我的代码:
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);
}
我在几个设备上测试了这段代码.它适用于普通的MP3播放器并假设教程是正确的,它也适用于Android手机.
但是使用两个不同的Windows手机运行此代码,我得到以下异常:
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)
在这一行:targetStream.Write(buffer,(int)optimalTransferSizeBytes,pcbWritten);
缓冲区大小为262144字节,而文件大小仅为75 KB.我希望有人知道如何解决这个问题.
问候
j0h4nn3s
最佳答案 我有同样的问题,结果是作者犯了一个简单的错误.您正在编写缓冲区的大小而不是您读取的字节数.
更换
targetStream.Write(buffer, (int)optimalTransferSizeBytes, pcbWritten);
通过
targetStream.Write(buffer, bytesRead, pcbWritten);