在C#中使用PortableDeviceAPI可以通过以下步骤进行:
-
添加对PortableDeviceApiLib库的引用。可以通过右键点击项目,选择“添加引用”,然后在COM选项卡中找到“PortableDeviceApiLib”并添加。
-
在代码中创建PortableDeviceManager对象,并使用其方法连接到设备。例如:
PortableDeviceManager deviceManager = new PortableDeviceManager(); deviceManager.RefreshDeviceList(); // 获取设备列表 string[] deviceIds = new string[1]; uint count = 1; deviceManager.GetDevices(deviceIds, ref count); // 连接到设备 PortableDevice device = new PortableDevice(); device.Open(deviceIds[0]);
- 使用PortableDevice对象进行操作,如获取设备信息、列举文件、上传和下载文件等。例如:
// 获取设备名称 string deviceName; device.GetDeviceFriendlyName(out deviceName); // 列举设备中的文件 IPortableDeviceContent content; device.Content(out content); IPortableDeviceProperties properties; content.Properties(out properties); IPortableDevicePropVariantCollection objectIds = new PortableDeviceTypesLib.PortableDevicePropVariantCollection() as IPortableDevicePropVariantCollection; content.EnumObjects(0, deviceIds[0], null, out objectIds); uint numObjects; objectIds.GetCount(out numObjects); for (uint i = 0; i < numObjects; i++) { var propertyValue = https://www.yisu.com/ask/new PortableDeviceApiLib._tagpropertykey();"文件名:" + fileName); } // 上传文件到设备 PortableDeviceApiLib.IPortableDeviceContent2 content2 = device as PortableDeviceApiLib.IPortableDeviceContent2; PortableDeviceApiLib.IStream wpdStream; content2.CreateObjectWithPropertiesAndData( PortableDevicePKeys.WPD_OBJECT_FORMAT_UNSPECIFIED, "test.jpg", null, out wpdStream, 0); FileStream fileStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read); byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = fileStream.Read(buffer, 0, buffer.Length); IntPtr pcbWritten = IntPtr.Zero; wpdStream.Write(buffer, (uint)bytesRead, pcbWritten); } while (bytesRead > 0); wpdStream.Commit(0); Marshal.ReleaseComObject(wpdStream);
以上是PortableDeviceAPI的基本用法,你可以根据自己的需求进行扩展和修改。